views:

938

answers:

4

How to get Last Index Of "%" in a string in .NET ? I tried

string subString = content.Substring(0, startIndex);
int nextOpeningComment = subString.LastIndexOf("%", 0);

This is always giving me -1.

Here subString I'm getting is:

<div id=\"xyz\">  \r\n    <img alt=\"\" src=\"App_Themes/Default/Images/abc.jpg\" />\r\n    <%--

Any help/suggestions appreciated.

+9  A: 

You're looking for occurrences of % but you're starting at position 0 and searching backwards from there. There's no % character at position 0, and that's why the LastIndexOf call is returning -1.

You need to start your search at the end of the string:

string subString = content.Substring(0, startIndex);
int nextOpeningComment = subString.LastIndexOf("%");
LukeH
Great..it worked....thanks....
Manish
+4  A: 

If there is no % in the string, then the return of -1 is expected and By Design. It indicates that the requested string is not present in the value "subString"

JaredPar
Thanks...but I really know this thing...and there is % in the string...
Manish
+10  A: 

It's because the method searches the string backwards, towards the beginning. By specifying start position 0, you tell it to start at the first character. Unless the first character is "%" it will return -1, regardless of what the rest of the string contains. Use the LastIndexOf overload without the start index and you should get the expected result.

Fredrik Mörk
content might have a % in it, but content.Substring(0, startIndex); might not :-)
ThePower
Ofcourse I'm confident...it's really not working...is it like "%" is a special symbol and requires some other treatment ??
Manish
Manish: see my updated answer: I realized (I think) what your problem is...
Fredrik Mörk
WOW !! worked like a charm..I thought it(0) is the start index from where it should start the search.Thanks Fredrik and thanks everyone...!!!
Manish
+3  A: 

there is no symbols from the end of the string starting from 0 try

content.LastIndexOf("%");
ArsenMkrt
Great...it worked...thanks....it was bcoz of the 0 !!
Manish