String array reverse Java

13,004

Solution 1

This line looks wrong:

for (int j = s[i].length()-1; i >= 0; i--)

It should be:

for (int j = s[i].length()-1; j >= 0; j--)

In other words: the indexes in the inner loop are mistaken, they should be using j instead of i. As a side comment - here's a simpler way to reverse a string:

reverse = new StringBuilder(s[i]).reverse().toString();

Solution 2

Try these steps:

String[] strDays = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday"};
List<String> list = Arrays.asList(strDays);
Collections.reverse(list);
strDays = (String[]) list.toArray();

Solution 3

Looks like you used i instead of j in the inner loop.

 for (int j=s[i].length()-1;j>=0;j--)
      reverse=reverse+s[i].charAt(j);

Solution 4

I'd advise you to break even this small problem into chunks.

Write a separate method that reverses a single String. Get that working and tested. Only then should you iterate over a collection or array and apply it to each member.

You'd have an easier time debugging this if you did it in smaller steps. The fact that your string reversing method was borked would have been apparent right away.

You shouldn't write stuff to System.out like that from methods.

public static String reverse(String s) {
    StringBuilder reversed = new StringBuilder(s.length());
    // reverse one string here
    return reversed.toString();
}

public static String [] reverseAll(String [] originals) {
    String [] reversed = new String[originals.length];
    for (int i = 0; i < originals.length; ++i) {
        reversed[i] = reverse(originals[i]);
    }
    return reversed;
}
Share:
13,004
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to reverse all the strings in an array in java, but seem to over write all of them with the first.

    private static void palindrome(String[] s) {
        int flag=0;
        String reverse;
        for(int i=0;i<n;i++) // n is declared globally as number of strings
        {
            reverse="";
            for (int j=s[i].length()-1;i>=0;i--)
                 reverse=reverse+s[i].charAt(j);
            if(s[i].equals(reverse))
                {
                    System.out.println(s[i]);   
                    flag=1;
                }
        }
        if(flag==0)
            System.out.println("There are no palindromic strings");
    }
    
  • Noor Hossain
    Noor Hossain about 4 years
    The best method, without time consume! great!