问题
I have strings that all have different lengths. e.g.
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#?
回答1:
string stringStart = str1.Substring(0, str1.IndexOf("----First Message-----"));
回答2:
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));
}
回答3:
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;
来源:https://stackoverflow.com/questions/9404182/cutting-a-string-before-a-special-character-everytime-in-c-sharp