how to check if the first half of a string is the same as the second half of the string? (not to be confused with palindromes) This is my code so far.
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");
}
Example String Input: abab
Output: It's the same
If your input is of length of odd number then its not same as second half.
if(sFB.length()%2!=0){
System.out.println("It's not the same");
}
Complete code as below.
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");
}
}
}
}