字符串比较使用char

时间:2016-06-21 17:15:31

标签: java string string-comparison

这段代码是否正确?

class Palindrome
{
    public static void main(String[] args)
    {
        String original = "Dot is Got";

        int len = original.length();

        for (int i = 0; i < len; i++) {
            char[] a = charAt[i];
        }

        for (int j = len; j >= 0; j++) {
            char[] b = charAt[j];
        }

        if (a[] == b[]) {
            System.out.print("Palindrome");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我想你试图实现的是这个:

String original = "Dot is Got";

int len = original.length();
char[] a = new char[len];
for (int i = 0; i < len; i++) {
    a[i] = original.charAt(i);
}
char[] b = new char[len];
for (int j = len - 1; j >= 0; j--) {
    b[len - 1 - j] = original.charAt(j);
}

if (Arrays.equals(a, b)) {
    System.out.print("Palindrome");
} else {
    System.out.print("Not a palindrome");
}

<强>输出:

Not a palindrome

答案 1 :(得分:0)

您的代码甚至无法编译。

for (int i= 0; i < len ; i++)
{    
    char[] a = charAt[i];
}

for (int j= len ; j>=0 ; j++)
{ 
   char[] b = charAt[j];    
}

这里你没有实例化长度为1的数组(a和b),它总是会被覆盖,而且你正在制作无法在循环外访问的局部变量。

您无法比较

等数组
if (a[]==b[])
{
    System. out. print("Palindrome");
}

你可以做的是

public static void main (String[] args)
{
    String original = "Dot is Got";
    StringBuilder sb = new StringBuilder(original);
    if(original.equals(sb.reverse().toString())) {
       System. out. print("Palindrome");
    } else {
       System. out. print("Not a palindrome");
    }
}

请参阅this以了解反向功能。

如果您仍然希望按照您的方式进行操作,那么您需要将代码更改为

public class Palindrome {
    public static void main (String[] args)
    {
        String original= "Dot is Got";
        int len = original.length();
        boolean palindrome = true;
        for (int i= 1; i <= len ; i++)
        {
            if( original.charAt(len-i) == original.charAt(i-i)) {
                continue;
            } else {
                palindrome = false;
                break;
            }
        }
        if(palindrome) {
            System.out.println("Palindrome");
        } else {
            System.out.println("Not a Palindrome");
        }
    }
}