Difference between two strings C#

前端 未结 6 908
小蘑菇
小蘑菇 2020-12-17 10:23

Lets say I have two strings:

string s1 = \"hello\";
string s2 = \"hello world\";

Is there a way I can get a string s3 = \" world\";

相关标签:
6条回答
  • 2020-12-17 10:25
    string s1 = "hello";
    string s2 = "hello world";
    string s3 = s2.replace(s1,"");
    
    0 讨论(0)
  • 2020-12-17 10:29

    Use string s3 = s2.Replace(s1, "");

    EDIT: Note that all occurrences of s1 in s2 will be absent from s3. Make sure to carefully consider the comments on this post to confirm this is your desired result, for example the scenarios mentioned in @mellamokb's comment.

    0 讨论(0)
  • 2020-12-17 10:29

    IF (big "if") s1 is always a substring of s2, then you could work with .IndexOf and .Length to find where in s2 that s1 is.

    0 讨论(0)
  • 2020-12-17 10:38

    If the case you define is correct an alternative solution would be:

    string s3 = s2.substring(s1.Length);
    

    This is presuming that the second string begins with exactly the same characters as the first string and you merely want to chop off the initial duplication.

    0 讨论(0)
  • 2020-12-17 10:42

    First answer without conditions outside of the code:

    string s3 = null;
    if (s2.StartsWith(s1))
    {
        s3 = s2.Substring(s1.Length);
    }
    
    0 讨论(0)
  • 2020-12-17 10:48

    With a simple replace

    string s3 = s2.Replace(s1, "");
    
    0 讨论(0)
提交回复
热议问题