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);
}
try this.
int startPosition = currentText.IndexOf("1 . 2 To Other Mobiles");
int endPosition = currentText.LastIndexOf("Total") + 5;
string result = currentText.Substring(startPosition, endPosition - startPosition);
You may use String.LastIndexOf()
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
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