2013-06-28 81 views
1

我想找到一種方法,如何比較兩個字符串並升級第一個,當第二個有更多的字符串時。 例如比較並更新一個字符串

String A="This is a statement!"; 
String B="This is a statement! Good luck!"; 
if(A<B{ //B has more letters 
     //Upgrade A } 
    else{ //Upgrade B 
     } 

我的意思是與升級不覆蓋像A = B。 我的字符串通常有很多行。 我想保留字符串的值,並從其他字符串插入新的東西。 有人有想法嗎?

編輯:謝謝你的好的答案。 不幸的是,我沒有把它更清楚,對不起我的錯。 我的問題是,我不知道現在在變化,串看起來是這樣的:

String A: 
A 
B 
C//Good morning, sir 
D//A comment 
E 


String B: 
A 
B//Yes 
C 
D 
DD 
E 

The result should be: 
A 
B//Yes 
C//Good morning, sir 
D//A comment 
DD 
E 
+1

什麼是升級?另外,如果字符串不共享前綴會發生什麼?請注意,Java沒有運算符重載,並且即使它具有,'<'也很可能會比較詞法排序。 –

+1

這段代碼不會編譯。 – 2013-06-28 14:24:18

+0

編寫「字符串長度Java」,您會驚訝於結果! – Maroun

回答

2

我想你需要的東西是這樣的:

String A="This is a statement!"; 
String B="This is a statement! Good luck!"; 

if (A.length() < B.length()){ //B has more letters 
     A += B.subString(A.length(), B.length()-1); 
} else{ 
     B += A.subString(B.length(), A.length()-1); 
} 

希望這是你在找什麼:)。

+0

謝謝。當然,這是我通過疏忽描述的問題的最佳解決方案。我會將其標記爲肯定的解決方案。 – Hayabusa

0

由長度比較字符串,使用string.length減() 例如

public class Test{ 
    public static void main(String args[]){ 
     String Str1 = new String("This is a statement!"); 
     String Str2 = new String("This is a statement! Good luck!"); 

    if(Str1.length() > Str2.length()) 
     Str2 += Str1; 
    else 
     Str1 += Str2; 
} 
0
String A = "This is a statement!"; 
String B = "This is a statement! Good luck!"; 
if (B.length() > A.length()) { //B has more letters 
    //Upgrade A 
} else { 
    //Upgrade B 
} 
+0

**史詩facepalm ** – SeniorJD

+0

@SeniorJD哦,我的好主人沒有注意.... – sunrize920

+1

複製粘貼是一個邪惡的=) – SeniorJD

1

這樣如何:

if(A.length() < B.length() { //B has more letters 
    //Upgrade A 
} 
else { //Upgrade B 

} 
+0

+1的升級評論:) –

0

比較Strings由長度:

if (A.length() > B.length()) { 
    B = A; 
} else { 
    A = B; 
} 
0

試試這個

if(!B.contains(A)){ 
    A = B; 
} 
0
if (B.length() > A.length()) { // upgrade B as it's longer 
} else if (A.length() > B.length()) { // upgrade A as its longer 
} else if (A.length() == B.length()) { // not sure what to do here as they're of equal length 
} 

除了空檢查,我相信這涵蓋了每一種可能的情況。

0

我的意思是你會使用subsString()length()的組合。以b.subString(a.length, b.length-1)並將該子字符串連接到a

0

使用String.length()比較大小,然後連接最長鏈的末尾。

String a="This is a statement!"; 
String b="This is a statement! Good luck!"; 

if(b.length() > a.length()) { 
    a = a.concat(b.substring(a.length())); 
} 
else if(a.length() > b.length()) 
{ 
    b = b.concat(a.substring(b.length())); 
} 
0

希望這會有所幫助。

if(A.contains(B) && !A.equals(B)) 
{ 
    A += B.substring(A.length(),B.length()); 
}