Home > Software design >  How to do I cut off a certain part a String?
How to do I cut off a certain part a String?

Time:09-20

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

CodePudding user response:

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 return 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.

CodePudding user response:

You have to do a substring, like the example below. See enter image description here

  •  Tags:  
  • c#
  • Related