如何在 C# 中根据字符串的长度读取子字符串 [英] How to Read Substrings based on Length of the String in C#

查看:59
本文介绍了如何在 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".怎么做?

解决方案

我必须在startPosition长度之后读取到最后位置长度

使用 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?

解决方案

I have to read after the startPosition length to last position length

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

What should i do if i need to read for the first "Total" only.

then use IndexOf instead:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆