0

I have an ArrayList with a number of entries, and I want to reverse the order or the characters, so if my code looks like this:

public class Test {

ArrayList<String> aa = new ArrayList<String>();

aa.add("hello");
aa.add("goodbye");

(reverse them in some way)


}

Then what I want the ArrayList to contain is:

olleh
eybdoog

I've only managed to change the order of the entries in the entire ArrayList with Collections.reverse, but that really doesn't do what I want to.

Roadhouse
  • 187
  • 3
  • 11
  • 4
    It's actually not the same thing. The OP wants to keep the order of the arraylist elements, but wants to replace each element with that element reversed as a string. – Chris Gerken Apr 24 '13 at 18:05

4 Answers4

3

The StringBuilder class (mutable strings) contains a reverse operation that switches the characters of the StringBuilder.

int size = aa.size();
for(int i = 0; i < size; ++i)
{
    StringBuilder builder = new StringBuilder(aa.get(i));
    builder.reverse();    //reverse the StringBuilder
    aa.set(i, builder.toString());
}
gparyani
  • 1,958
  • 3
  • 26
  • 39
1

Quick and dirty version - changing the Strings inside the original ArrayList:

for(int i = 0; i < aa.size(); i++) {
    aa.set(i, new StringBuilder(aa.get(i)).reverse().toString());
}
Darwind
  • 7,284
  • 3
  • 49
  • 48
0

This is a linear time implementation, modifying the list in place.

public void reverseStr(List<String> theArgs) {
   for(int i = 0; i < theArgs.size(); i++) {
       String s = theArgs.get(i);
       theArgs.set(i, new StringBuffer(s).reverse().toString());
   }
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
-2

do it like this:

Best way to reverse a string

    static void Main(string[] args)
    {
        var aa = new List<String>();

        aa.Add("hello");
        aa.Add("goodbye");

        var x = from s in aa select Reverse(s);

        foreach (var c in x)
            Console.WriteLine(c.ToString( ));

        Console.ReadLine();
    }

    public static string Reverse(string s)
    {
        char[] charArray = s.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
Community
  • 1
  • 1
Timmerz
  • 6,090
  • 5
  • 36
  • 49