我有一个包含子字符串的字符串,其中一个是“ 1. 2 To Other Mobiles”,另一个是“ Total”。现在,根据我的要求,我必须阅读第一个子字符串之间的内容,即“.1。2To Other Mobiles”和“总计”。我正在按照c#中的代码进行操作。
int startPosition = currentText.IndexOf("1 . 2 To Other Mobiles");
int endPosition = currentText.IndexOf("Total");
string result = currentText.Substring(startPosition, endPosition - startPosition);
但是我面临的问题是“总计”在我的子字符串中是很多次。.我必须在startPosition长度之后读取到最后一个位置长度,即“总计”。怎么做?
我必须在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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句