一种计算字符串中的回文的方法

时间:2015-07-22 08:36:35

标签: java palindrome

我想创建一个计算String中的回文的方法,到目前为止,这就是我所做的:

public static int pal(String s) {
    int R = 0;
    int count = 0;
    int i = 0;
    char[] charArray = s.toCharArray();
    //this is suppose to be for word extraction from the sentence
    while (R <s.length()) {
        char ch = s.charAt(R);

        //this is for palindrom counting
        if (ch == ' ' || !Character.isLetter(ch)
            while(i < charArray.length) {
                if(charArray[i] == charArray[charArray.length - i - 1]) {
                    count++;
                }
                else {
                    System.out.println("not a palindrome");
                    //break;
                }
            }
        return count;
    }
    return 0;
}

我想在检查单词是否是回文之前从'String'中提取单词。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

public void palindrome(String string) {
    char[] charArray = string.toCharArray();
    int count = 0;
    int i = 0;

    while (i < charArray.length) {
        if(charArray[i] == charArray[charArray.length - i - 1]) {
            count++;
            i++;
        }
    }
    System.out.println("Count = " + count);
}

答案 1 :(得分:0)

 StringTokenizer st = new StringTokenizer(*your string here*);
     while (st.hasMoreTokens()) {
        //your code here
     }

例如:

 StringTokenizer st = new StringTokenizer("Your inserted string");
 while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
 }

结果:

 Your
 inserted
 string

答案 2 :(得分:0)

使用扫描仪

int nrOfPalindromes = 0;
Scanner sc = new Scanner(theString);
while(sc.hasNext(){
    if(isPalindrome(sc.next()){
        nrOfPalindromes++;
    }
}
System.out.println(nrOfPalindromes);