如何检查字符串的前半部分是否与字符串的后半部分相同?

How do you check if the first half of a string is the same as the second half of the string?

如何检查字符串的前半部分和后半部分是否相同? (不要与回文混淆)到目前为止,这是我的代码。

   Scanner oIn = new Scanner (System.in);
   String sFB = oIn.nextLine();
   int length = sFB.length();

   boolean bYes = true;
   char cA, cB;

   for (int i = 0; i < length/2; i++){
      cA = sFB.charAt(i);
      cB = sFB.charAt(/*what do i put here?*/);

       if (cA != cB){
           bYes = false;
           break;
       }
   }

   if (bYes) {
       System.out.println("It's the same");
   }
   else {
       System.out.println("It's not the same");
   }

示例字符串输入: 阿布

输出: 一样的

你有两种情况:如果字符串的长度是 odd 或者 even.

要检查一个字符串 s 是偶数还是奇数,你 % 它的长度。

要解决您的算法,请将其替换为:

 cB = sFB.charAt(i + length / 2);

您也可以在字符串 class 中使用 substring

您可以使用substring获取上半部分和下半部分。

public static boolean sameAsHalf(String s){

    if(s.length() == 1){
        return true;
    }

    if(s.length() % 2 == 0){

        String firstHalf = s.substring(0, s.length()/2);
        System.out.println(firstHalf);

        String secondHalf = s.substring(s.length()/2);
        System.out.println(secondHalf);
        return firstHalf.equals(secondHalf);
    }

    return false;
}

如果您来自其他语言,请使用equals检查字符串的内容是否相等。

如果您输入的是奇数长度,那么它与后半部分不同。

if(sFB.length()%2!=0){
System.out.println("It's not the same");
}

完整代码如下

public class StringEqualsSecondHalf {

public static void main(String[] args) {
    String sFB="String";
    if(sFB.length()%2!=0){
        System.out.println("Its not same");
    }
    else{
        String firstHalf=sFB.substring(0,sFB.length()/2);
        System.out.println("First Half "+firstHalf);
        String secondHalf=sFB.substring(sFB.length()/2,sFB.length());
        System.out.println("Second Half "+secondHalf);
        if(firstHalf.equals(secondHalf)){
            System.out.println("They are same");
        }
        else{
            System.out.println("They are not same");
        }
    }

}

}

public static boolean halfEquals(String string) {

    char[] stringArray = string.toCharArray();

    int firstHalfEnd = (stringArray.length / 2);
    int seconHalfStart = (stringArray.length / 2) + (stringArray.length % 2);

    for (int position = 0; position <  firstHalfEnd; position++) {
        if (stringArray[position] != stringArray[position + seconHalfStart]) {
            return false;
        }
    }

    return true;
}

String.toCharArray() 是关键,比 charAt() 简单得多。

编辑输出:

abab ->true

abcab ->true

abde ->false

abcde ->false

x ->真

->真