简体   繁体   中英

Cutting a String before a special character everytime in C#

I have strings that all have different lengths. eg

str1 = "This is new job ----First Message----- This is reopened ";
str2 = "Start Process ----First Message----- Is this process closed? <br/> no ----First Message-----";

Now these string shall always have the "----First Message-----" in it. What I need is to trim or split the string in such a way that I only get the part left of the FIRST TIME the "----First Message-----" occurs.

So in case of str1 result should be "This is new job " For str2 it should be "Start Process "

How can this be done in C#?

string stringStart = str1.Substring(0, str1.IndexOf("----First Message-----"));
String result = input.Substring(0, input.IndexOf('---FirstMessage-----'));

actually, for teaching purposes...

private String GetTextUpToFirstMessage( String input ){
    const string token = "---FirstMessage-----";
    return input.Substring(0, input.IndexOf(token));
}

This sounds like a job for REGULAR EXPRESSIONS!!!!

try the following code. don't forget to include the using System.Text.RegularExpressions; statement at the top.

    Regex regex = new Regex(@"^(.*)----FirstMessage----$");
    string myString = regex.Match(str1).Value;

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