給定兩個字符串,如果任何一個字符串出現在另一個字符串的最後,則返回true,忽略大小寫差異(換句話說,計算不應該是「區分大小寫」)。注意:str.toLowerCase()返回字符串的小寫版本。重構這個長而簡單的代碼 - 字符串比較
endOther( 「Hiabc」, 「ABC」)→真
endOther( 「ABC」, 「HiaBc」)→真
endOther( 「ABC」, 「abXabc」)→真
public class endOtherClass{
public static void main(String args[]) {
boolean is = endOther("yz","12xz") ;
System.out.println(is) ;
}
public static boolean endOther(String a, String b) {
a = a.toLowerCase() ;
b = b.toLowerCase() ;
if(a.length() == b.length()){
System.out.println("a and b have same length!") ;
if(a.equals(b)){
System.out.println("wow, even better - they are exact same") ;
return true ;
}
else {
System.out.println("but are diff!") ;
return false ;
}
}
String shorter = "" ;// figure out which - a or b - is shorter
String longer = "" ;// and which one is longer
if(a.length() > b.length()){ shorter = b ; longer = a ;}
else { shorter = a ; longer = b ;}
int offset = longer.length() - shorter.length() ; // the offset is used to know where exactly to start comparing
//go through the shorter and compare the corresponding part of the longer string
for(int i = 0 ; i < shorter.length() ; i++){
System.out.println("comparing subs: " + shorter.substring(i,i+1) + " and " + longer.substring(offset+i, offset+i+1)) ;
if(!shorter.substring(i,i+1).equals(longer.substring(offset+i, offset+i+1))){ //we add offset so we can start comparing the last n characters of shorter string!
System.out.println("something wrong in long: " + longer.substring(offset+i, offset+i+1)) ;
System.out.println("something wrong in short: " + shorter.substring(i,i+1)) ;
return false ;
}
}
return true ;
}
}
IM 90%肯定這個代碼可以簡化,但我不知道其他邏輯或思考這個簡單的練習
有人可以幫助我重構它,讓它更小的方式嗎?
這可能更適合[codereview.se] – MarioDS 2013-05-12 10:34:33