Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET string IndexOf unexpected result

A string variable str contains the following somewhere inside it: se\">

I'm trying to find the beginning of it using:

str.IndexOf("se\\\">")  

which returns -1

Why isn't it finding the substring?

Note: due to editing the snippet showed 5x \ for a while, the original had 3 in a row.

like image 547
Sajee Avatar asked Dec 20 '25 02:12

Sajee


2 Answers

Your code is in fact searching for 'se\\">'. When searching for strings including backslashes I usually find it easier to use verbatim strings:

str.IndexOf(@"se\"">")

In this case you also have a quote in the search string, so there is still some escaping, but I personally find it easier to read.

Update: my answer was based on the edit that introduced extra slashes in the parameter to the IndexOf call. Based on current version, I would place my bet on str simply not containing the expected character sequence.

Update 2: Based on the comments on this answer, it seems to be some confusion regarding the role of the '\' character in the strings. When you inspect a string in the Visual Studio debugger, it will be displayed with escaping characters.

So, if you have a text box and type 'c:\' in it, inspecting the Text property in the debugger will show 'c:\\'. An extra backslash is added for escaping purposes. The actual string content is still 'c:\' (which can be verified by checking the Length property of the string; it will be 3, not 4).

If we take the following string (taken from the comment below)

" '<em class=\"correct_response\">a night light</em><br /><br /><table width=\"100%\"><tr><td class=\"right\">Ingrid</td></tr></table>')"

...the \" sequences are simply escaped quotation marks; the backslashes are not part of the string content. So, you are in fact looking for 'se">', not 'se\">'. Either of these will work:

str.IndexOf(@"se"">");  // verbatim string; escape quotation mark by doubling it
str.IndexOf("se\">");   // regular string; escape quotation mark using backslash
like image 164
Fredrik Mörk Avatar answered Dec 22 '25 17:12

Fredrik Mörk


This works:

string str = "<case\\\">";
int i = str.IndexOf("se\\\">"); // i = 3

Maybe you're not correctly escaping one of the two strings?

EDIT there's an extra couple of \ in the string you are searching for.

like image 23
Paolo Tedesco Avatar answered Dec 22 '25 18:12

Paolo Tedesco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!