String array reverse Java

笑着哭i 提交于 2019-12-12 18:22:41

问题


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");
}

回答1:


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);



回答2:


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();



回答3:


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;
}



回答4:


Try these steps:

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



回答5:


Your inner loop should be:

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



回答6:


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

you need to correct your inner loop. Instead of i you need to use loop variable j.




回答7:


Why are you using this:

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

You should use this instead:

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


来源:https://stackoverflow.com/questions/22282845/string-array-reverse-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!