user3242607
user3242607

Reputation: 219

How to convert ArrayList<String> to char Array and then print each word backwards?

I have an ArrayList method that accepts an ArrayList and needs to return the words in reverse order. I know i need to use toCharArray and once i print them backwords i need to add it back to the ArrayList. Code is below.

Sample output should be cat dog

should be

tac god

public static ArrayList<String> reverseWordLetters(ArrayList<String> textArray)
{
    ArrayList<String> results = new ArrayList<String>(textArray.size());
    char [] c = new char[textArray.size()];
    for(int i = 0; i < textArray.size(); i ++)
    {
        c = textArray.get(i).toCharArray();
    }

    return results;
}

Upvotes: 0

Views: 2881

Answers (3)

Joe
Joe

Reputation: 99

public static ArrayList<String> foo(ArrayList<String> list){
    //if the list is empty or null return
    if(list == null || list.isEmpty()){
        return list;
    }
    //go through each string item in the list
    for(int i = 0; i < list.size(); i++){
        /*
         * get the first string and convert it to char 
         * array so we can reverse the string
         */
        String s = list.remove(0);
        char c[] = s.toCharArray();

        //reverse the string
        for(int j = 0; j < c.length/2; j++){
            char tmp = c[j];
            c[j] = c[c.length-j-1];
            c[c.length-j-1] = tmp;
        }

        /*
         * add the reverse string to 
         * the end of the list
         */
        list.add(new String(c));
    }

    /*
     * return the list of strings which will
     * be in the same order but the string 
     * itself will be reversed
     */
    return list;
}

Upvotes: 0

Nuno Ferreira
Nuno Ferreira

Reputation: 11

public static String reverse(String string) {

        char[] charArray = string.toCharArray();

        char tempChar;

        for (int i = 0, j = charArray.length - 1 ; i < charArray.length / 2; i++, j--) {

            tempChar = charArray[i];

            charArray[i] = charArray [j];

            charArray[j] = tempChar; 
        }

        return new String(charArray);
    }

For simple reverse (i.e. if you don't care about things like Character.MIN_SURROGATE or Character.MAX_SURROGATE) then the method above is more than enough and will be slightly more efficient than using the StringBuilder in terms of CPU and Memory (i.e. if volume is a concern).

CPU: In a test that repeated 100 million times executing the reverse method above and the one provided by the StringBuilder, the method above took only 55% of the time that is taken by StringBuilder.

MEMORY: In terms of memory the method above creates one less object in the Heap (the StringBuilder object is not created)

Upvotes: 1

Ashu Pachauri
Ashu Pachauri

Reputation: 1403

for(String s: textArray) {
    results.add(new StringBuilder(s).reverse().toString())
}

Upvotes: 3

Related Questions