如何根据C#中字符串的长度读取子字符串

我有一个字符串,其中包含一个子字符串其中一个是“1.2 To Other Mobiles”,另一个是“Total”。现在根据我的要求,我必须阅读第一个子字符串之间的内容,即“.1.2到其他手机“和”总计“。我是通过在c#中使用代码来实现的。

int startPosition = currentText.IndexOf("1 . 2 To Other Mobiles"); int endPosition = currentText.IndexOf("Total"); string result = currentText.Substring(startPosition, endPosition - startPosition); 

但是我面临的问题是“Total”在我的子串中很多次。我必须在startPosition长度之后读取最后一个位置长度,即“Total”。 怎么做?

我必须在startPosition长度后读取最后一个位置长度

使用LastIndexOf

 string search1 = "1 . 2 To Other Mobiles"; string search2 = "Total"; int startPosition = currentText.IndexOf(search1); if(startPosition >= 0) { startPosition += search1.Length; int endPosition = currentText.LastIndexOf(search2); if (endPosition > startPosition) { string result = currentText.Substring(startPosition, endPosition - startPosition); } } 

如果我只需要阅读第一个“总计”,我该怎么办?

然后使用IndexOf代替:

 // ... int endPosition = currentText.IndexOf(search2); if (endPosition > startPosition) { string result = currentText.Substring(startPosition, endPosition - startPosition); } 

试试这个。

 int startPosition = currentText.IndexOf("1 . 2 To Other Mobiles"); int endPosition = currentText.LastIndexOf("Total") + 5; string result = currentText.Substring(startPosition, endPosition - startPosition); 

你可以使用String.LastIndexOf()

问题:您没有添加第一个搜索字符串1 . 2 To Other MobilessubstringTotal的长度1 . 2 To Other MobilessubstringTotal 1 . 2 To Other MobilessubstringTotal

方案:

 string currentText = "1 . 2 To Other MobilessubstringTotal"; string search1="1 . 2 To Other Mobiles"; string search2="Total"; int startPosition = currentText.IndexOf(search1); int endPosition = currentText.IndexOf(search2); string result = currentText.Substring((startPosition+search1.Length), endPosition - (startPosition+search1.Length)); 

输出:

result => substring

你是这个意思?

 string currentText = "1 . 2 To Other Mobiles fkldsjkfkjslfklsdfjk Total"; string text = "1 . 2 To Other Mobiles"; int startPosition = currentText.IndexOf("1 . 2 To Other Mobiles"); int endPosition = currentText.IndexOf("Total"); string result = currentText.Substring(startPosition + text.Length, endPosition - (startPosition + text.Length)); 

在文本“1.2 To Other Mobiles fkldsjkfkjslfklsdfjk Total”中;

输出将是:

fkldsjkfkjslfklsdfjk