3

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#?

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
user970225
  • 145
  • 3
  • 5
  • 16
  • Possible duplicate of [Get Substring - everything before certain char](http://stackoverflow.com/questions/1857513/get-substring-everything-before-certain-char) – Michael Freidgeim Jan 14 '17 at 12:35

3 Answers3

13
string stringStart = str1.Substring(0, str1.IndexOf("----First Message-----"));
phoog
  • 42,068
  • 6
  • 79
  • 117
  • This returns the string you want so make sure to capture it in a variable if you want to use it later, etc. It doesn't modify str1's contents. http://msdn.microsoft.com/en-us/library/aka44szs.aspx – Josh P Feb 22 '12 at 22:36
  • @JoshP thanks for pointing that out; I've edited the answer to take it into account. – phoog Feb 22 '12 at 22:38
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));
}
mindandmedia
  • 6,800
  • 1
  • 24
  • 33
0

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;
  • can you check this Question http://stackoverflow.com/questions/19131758/how-to-split-a-string-into-an-array-of-strings – Anjali Oct 02 '13 at 15:00
  • Now you have two problems.... the $ at the end will ensure that you don't get a match with the data in the question. – Dominic Cronin Sep 05 '17 at 21:34