How to do I cut off a certain part a String?

Viewed 72

I have a big String in my program. For Example:

String Newspaper = "...Blablabla... What do you like?...Blablabla... ";

Now I want to cut out the "What do you like?" an write it to a new String. But the problem is that the "Blablabla" is everytime something diffrent. Whit "cut out" I mean that you submit a start and a end word and all the things wrote between these lines should be in the new string. Because the sentence "What do you like?" changes sometimes except the start word "What" and the end word "like?"

Thanks for every responds

3 Answers

You can write the following method:

public static string CutOut(string s, string start, string end)
{
    int startIndex = s.IndexOf(start);
    if (startIndex == -1) {
        return null;
    }
    int endIndex = s.IndexOf(end, startIndex);
    if (endIndex == -1) {
        return null;
    }
    return s.Substring(startIndex, endIndex - startIndex + end.Length);
}

It returns null if either the start or end pattern is not found. Only end patterns that follow the start pattern are searched for.

If you are working with C# 8+ and .NET Core 3.0+, you can also replace the last line with

    return s[startIndex..(endIndex + end.Length)];

Test:

string input = "...Blablabla... What do you like?...Blablabla... ";
Console.WriteLine(CutOut(input, "What ", " like?"));

prints:

What do you like?

If you are happy with Regex, you can also write:

public static string CutOutRegex(string s, string start, string end)
{
    Match match = Regex.Match(s, $@"\b{Regex.Escape(start)}.*{Regex.Escape(end)}");
    if (match.Success) {
        return match.Value;
    }
    return null;
}

The \b ensures that the start pattern is only found at the beginning of a word. You can drop it if you want. Also, if the end pattern occurs more than once, the result will include all of them unlike the first example with IndexOf which will only include the first one.

You have to do a substring, like the example below. See source for more information on substrings.

// A long string    
string bio = "Mahesh Chand is a founder of C# Corner. Mahesh is also an 
author, speaker, and software architect. Mahesh founded C# Corner in 
2000.";    
    
// Get first 12 characters substring from a string    
string authorName = bio.Substring(0, 12);    
Console.WriteLine(authorName);

In this case I would do it like this, cut the first part and then the second and concatenate with the fixed words using them as a parameter for cutting.

    public string CutPhrase(string phrase)
    {
        var fst = "What";
        var snd = "like?";

        string[] cut1 = phrase.Split(new[] { fst }, StringSplitOptions.None);
        string[] cut2 = cut1[1].Split(new[] { snd }, StringSplitOptions.None);

        var rst = $"{fst} {cut2[0]} {snd}";

        return rst;
    }

enter image description here

Related