我有一个字符串,其中包含数字破折号和数字,因此可以
1-2
234-45
23-8
它可以是任何数字的任何序列,最多12个字符。
这些所有数字前面都有一个字符串。我需要在此序列开始之前提取此字符串。
This is a Test1 1-2
This is a test for the first time 234-45
This is a test that is good 23-8
所以我需要提取
This is a Test1
This is a test for the first time
This is a test that is good
此字符串与序列之间只有一个空格。
有什么方法可以提取那个字符串。拆分方法在这里不起作用。 我忘了提到我在字符串之前有数字/测试,所以它可以是
2123 This is a test for the first time 23-456
或
Ac23 This is a test for the first time 23-457
任何帮助将不胜感激。
答案 0 :(得分:1)
以这种方式:
var sample = "2123 This is a Test1 1-2";
// Find the first occurrence of a space, and record the position of
// the next letter
var start = sample.IndexOf(' ') + 1;
// Pull from the string everything starting with the index found above
// to the last space (accounting for the difference from the starting index)
var text = sample.Substring(start, sample.LastIndexOf(' ') - start);
在此之后,text
应该等于:
这是一个Test1
将它包裹在一个漂亮的小函数中并通过它发送你的字符串集合:
string ParseTextFromLine(string input)
{
var start = input.IndexOf(' ') + 1;
return input.Substring(start, input.LastIndexOf(' ') - start);
}
答案 1 :(得分:0)
这很简单,
string s = "This is a Test1 1-2";
s = s.Substring(0,s.LastIndexOf(" ");
现在s将是“This is a Test1”