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
4

11 回答 11

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);
}

希望这是您正在寻找的:)。

于 2013-06-28T14:28:47.710 回答
1

这个怎么样:

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

}
于 2013-06-28T14:26:46.100 回答
0

用于String.length()获取字符串的长度。

于 2013-06-28T14:25:39.190 回答
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;
}
于 2013-06-28T14:26:03.477 回答
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
}
于 2013-06-28T14:26:32.573 回答
0

比较Strings按长度:

if (A.length() > B.length()) {
    B = A;
} else {
    A = B;
}
于 2013-06-28T14:26:53.797 回答
0

试试这个

if(!B.contains(A)){
   A = B;
}
于 2013-06-28T14:27:15.463 回答
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
}

除了空值检查之外,我相信这包括所有可能的情况。

于 2013-06-28T14:27:33.923 回答
0

我的意思是你将使用subsString()和的组合length()。获取b.subString(a.length, b.length-1)并将该子字符串连接到a

于 2013-06-28T14:29:01.503 回答
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()));
}
于 2013-06-28T14:29:28.160 回答
0

希望这可以帮助。

if(A.contains(B) && !A.equals(B))
{
  A += B.substring(A.length(),B.length());
}
于 2013-06-28T14:39:37.607 回答