本文介绍了如何在 C# 中根据字符串的长度读取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含子字符串的字符串,其中一个是1 . 2 到其他手机",另一个是总计".现在根据我的要求,我必须阅读第一个子字符串之间的内容,即 ."1 . 2To Other Mobiles"和Total".我是按照 c# 中的代码来做的.

int startPosition = currentText.IndexOf("1 . 2 To Other Mobiles");int endPosition = currentText.IndexOf("Total");字符串结果 = currentText.Substring(startPosition, endPosition - startPosition);

但我面临的问题是Total"在我的子字符串中多次出现.我必须在 startPosition 长度之后阅读到最后一个位置长度,即Total".怎么做?

解决方案

使用 LastIndexOf:

string search1 = "1 . 2 到其他手机";string search2 = "总计";int startPosition = currentText.IndexOf(search1);如果(起始位置 >= 0){startPosition += search1.Length;int endPosition = currentText.LastIndexOf(search2);if (endPosition > startPosition){字符串结果 = currentText.Substring(startPosition, endPosition - startPosition);}}

如果我只需要阅读第一个总计"该怎么办.

然后使用 IndexOf 代替:

//...int endPosition = currentText.IndexOf(search2);if (endPosition > startPosition){字符串结果 = currentText.Substring(startPosition, endPosition - startPosition);}

I have a String which contains a substrings One of them is "1 . 2 To Other Mobiles" and other is "Total".Now as per my requirement i have to read the Contents between first substring i.e ."1 . 2 To Other Mobiles" and "Total".I am doing it by following code in c#.

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

But the problem that i am facing is "Total" is Many times in my substring..I have to read after the startPosition length to last position length i.e. "Total".How to do it?

解决方案

Use 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);
    }
}

then use IndexOf instead:

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

这篇关于如何在 C# 中根据字符串的长度读取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:10