Lets say I have two strings:
string s1 = \"hello\";
string s2 = \"hello world\";
Is there a way I can get a string s3 = \" world\";
string s1 = "hello";
string s2 = "hello world";
string s3 = s2.replace(s1,"");
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.
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.
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.
First answer without conditions outside of the code:
string s3 = null;
if (s2.StartsWith(s1))
{
s3 = s2.Substring(s1.Length);
}
With a simple replace
string s3 = s2.Replace(s1, "");