两个字符串C#之间的区别
可以说我有两个字符串:
string s1 = "hello"; string s2 = "hello world";
有没有办法让我得到一个string s3 = " world";
这两个字符串之间的区别是什么?
编辑:
在这种情况下,差异将始终存在
s1 = "abc" s2 = "abcd ads as "
使用string s3 = s2.Replace(s1, "");
编辑:请注意, s3
中将缺少s2
中所有出现的s1
。 请务必仔细考虑此post上的评论,以确认这是您想要的结果,例如@mellamokb评论中提到的情景。
string s1 = "hello"; string s2 = "hello world"; string s3 = s2.replace(s1,"");
如果您定义的案例是正确的,则替代解决方案将是:
string s3 = s2.substring(s1.Length);
这假设第二个字符串以与第一个字符串完全相同的字符开头,您只想切断初始复制。
用简单的替换
string s3 = s2.Replace(s1, "");
IF(大“如果”) s1
始终是s2
的子串,那么你可以使用.IndexOf
和.IndexOf
来找到s2
中s1
位置。
在代码之外没有条件的第一个答案:
string s3 = null; if (s2.StartsWith(s1)) { s3 = s2.Substring(s1.Length); }