Cutting a String before a special character everytime in C#

妖精的绣舞 提交于 2020-01-23 13:10:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!