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