本文介绍了String数组反向的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图扭转在Java数组中的所有字符串,但似乎在写他们都与第一。

 私有静态无效回文(字符串[] S){
    INT标志= 0;
    串逆转;
    的for(int i = 0; I< N;我++)// n为全局声明为字符串的数
    {
        反向=;
        对于(INT J = S [I]。长度() - 1; I> = 0;我 - )
             反向=反转+ S [I] .charAt(J);
        如果(S [i]于.equals(反向))
            {
                的System.out.println(S [I]);
                标志= 1;
            }
    }
    如果(标志== 0)
        的System.out.println(没有回文字符串);
}


解决方案

这行看起来错误的:

 的for(int J = S [I]。长度() -  1; I> = 0;我 - )

它应该是:

 的for(int J = S [I]。长度() -  1; J> = 0; j--)

在换句话说:在内部循环的指标是错误的,他们应该使用Ĵ而不是 I 。作为一个边评论 - 这里的扭转一个字符串更简单的方式:

 反向=新的StringBuilder(S [I])反向()的toString()。

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");
}
解决方案

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

这篇关于String数组反向的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 16:49
查看更多