compare and update a string

2019-08-07 17:01发布

I am trying to find a way, how to compare two strings and upgrade the first, when the second has more in it. For example

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
      }

I mean with upgrade not overwriting like A=B. My strings has usually much lines. I want to keep the value of the string and just insert the new things from the other String. Has someone an idea?

EDIT: Thank you for the nice answers. Unfortunetly I didnt exlain it more clear, sorry my fault. My problem is, that I do now know where the changes are, the strings could look like this:

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

11条回答
神经病院院长
2楼-- · 2019-08-07 17:06

Hope this helps.

if(A.contains(B) && !A.equals(B))
{
  A += B.substring(A.length(),B.length());
}
查看更多
时光不老,我们不散
3楼-- · 2019-08-07 17:14

Compare strings by length, using String.length() For example

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;
}
查看更多
时光不老,我们不散
4楼-- · 2019-08-07 17:15
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
}
查看更多
爷的心禁止访问
5楼-- · 2019-08-07 17:23

Use String.length() to compare the size then concat the end of the longest chain.

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()));
}
查看更多
够拽才男人
6楼-- · 2019-08-07 17:24

I guess you need something like this:

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

Hope this is what you are looking for :).

查看更多
男人必须洒脱
7楼-- · 2019-08-07 17:24

Compare the Strings by length:

if (A.length() > B.length()) {
    B = A;
} else {
    A = B;
}
查看更多
登录 后发表回答