简体   繁体   中英

Deleting a string from another string c#

I want to subtract an inputted string from another inputted string, however the operator "-" is not allowed with strings. Example

s1 = "abcdhello";
s2 = "hellothere";
//i want s3 to be like:
s3 = "abcd";

How can i achieve this, i tried .substring, but it didn't work out.

Update: Let's say i have a key and text, let's consider s1 as a combinedkey, and s2 as the text, i want to get the uncombinedkey.

loop through s1 and s2 finding the longest overlap and returning the difference, or the original value

public static string GetWeird(string s1, string s2)
{
    Console.WriteLine(s1);
    for (int i = Math.Max(0, s1.Length - s2.Length); i < s1.Length; i++)
    {
        var ss1 = s1.Substring(i, s1.Length - i);
        var ss2 = s2.Substring(0, Math.Min(s2.Length, ss1.Length));
        Console.WriteLine(ss2.PadLeft(s1.Length));
        if (ss1 == ss2)
            return s1.Substring(0, i);
    }

    return s1;
}

public static void Main()
{
    var s1 = "5675675756756abcdhello";
    var s2 = "hellothere";
    var s3 = GetWeird(s1, s2);
    Console.WriteLine(s3);
}

Output

5675675756756abcdhello
            hellothere
             hellother
              hellothe
               helloth
                hellot
                 hello
5675675756756abcd

Full Demo Here

Convert both strings to lists of chars and remove chars in the first list if they are in the second.

As simple as that

string s1 = "abcdefg";
string s2 = "efghijk";

List<char> s1l = s1.ToList();
List<char> s2l = s2.ToList();

s1l.RemoveAll(c => s2l.ToList().Exists(n => n == c));

string s3 = String.Concat(s1l);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM