How to Read Substrings based on Length of the Stri

2020-04-21 02:09发布

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?

5条回答
我只想做你的唯一
2楼-- · 2020-04-21 02:31
来,给爷笑一个
3楼-- · 2020-04-21 02:34

Problem : you are not adding the length of the first search string 1 . 2 To Other MobilessubstringTotal

Solution :

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

Output:

result => substring

查看更多
Fickle 薄情
4楼-- · 2020-04-21 02:37

try this.

int startPosition = currentText.IndexOf("1 . 2 To Other Mobiles");
int endPosition = currentText.LastIndexOf("Total") + 5;
string result = currentText.Substring(startPosition, endPosition - startPosition);
查看更多
Juvenile、少年°
5楼-- · 2020-04-21 02:42

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);
}
查看更多
▲ chillily
6楼-- · 2020-04-21 02:50

You mean this?

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

In the text "1 . 2 To Other Mobiles fkldsjkfkjslfklsdfjk Total";

The output will be:

fkldsjkfkjslfklsdfjk

查看更多
登录 后发表回答