[英]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. 现在这些字符串应始终包含
"----First Message-----"
。 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. 我需要的是修剪或分割字符串,使得我只得到第一次剩下的部分
"----First Message-----"
。
So in case of str1
result should be "This is new job " For str2
it should be "Start Process "
所以在
str1
结果的情况下应该是“这是新工作”对于str2
应该是"Start Process "
How can this be done in C#? 如何在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!!!! 这听起来像是REGULAR EXPRESSIONS的工作!!!!
try the following code. 尝试以下代码。 don't forget to include the
using System.Text.RegularExpressions;
不要忘记包含
using System.Text.RegularExpressions;
statement at the top. 在顶部的声明。
Regex regex = new Regex(@"^(.*)----FirstMessage----$");
string myString = regex.Match(str1).Value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.