我正在嘗試編寫一個程序來檢查字符串的前兩個字母和最後兩個字母是否相同。例如,frontAgain(「編輯」);應該返回true。但是,以下程序僅適用於2個字符串,如「ed」。我想,所以我試圖用線條喜歡這可能是一個對象比較的問題:比較java中的數組字符串以獲得布爾值
splitstring[0].equals(splitstring[length - 2])
splitstring[0] == splitstring[length - 2]
splitstring[0].equalsIgnoreCase(splitstring[length - 2])
但再次我的程序只工作了像「ED」的字符串。有任何想法嗎?這裏是我的代碼:
public class Mainjazz {
public static boolean frontAgain(String str){
int length = str.length(); //gets length of string for later use in if statement
String[] splitstring = str.split(""); //splits string into an array
if((splitstring[0].equals(splitstring[length - 2])) && (splitstring[1].equals(splitstring[length - 1]))){ //checks if first two letters = last two
return true;
}else{
return false;
}
}
public static void main(String[] args) {
System.out.println(frontAgain("edited"));
}
}
編輯:問題解決了,謝謝:)
它爲什麼會超過2個字符的工作時,你只比較兩個字符? –