开发者

Difference between two strings C#

Lets say I have two strings:

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

Is there a way I can get a string s3 = " world"; which is the difference between the 2 strings?

EDIT:

The difference will be always in this scenario

s1 = "abc"
s2 =开发者_StackOverflow社区 "abcd ads as "


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.


string s1 = "hello";
string s2 = "hello world";
string s3 = s2.replace(s1,"");


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.


With a simple replace

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


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.


First answer without conditions outside of the code:

string s3 = null;
if (s2.StartsWith(s1))
{
    s3 = s2.Substring(s1.Length);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜