问题
Could someone point me why the IndexOf returns always zero in the following text?
Dim Str as string = "<p><img class=floatLeft width="330"src="http://www.com"></p><p>"
Dim Idx as integer = Str.IndexOf("<p>")
Is there any other way, of getting the index?
回答1:
Because the first occurrence of <p> is at the beginning of the string, and strings (along with many other things) are zero-indexed.
If you want to get the index of the last-occurring <p>, you can use Str.LastIndexOf("<p>").
If you want to get the index of the next-occurring <p> after the first, and assuming the string always starts with at least one <p>, you can use Str.IndexOf("<p>", "<p>".Length()) so it starts searching from after the first occurrence.
By the way, you have a syntax error in your Dim Str line, you need to escape double quotes with extra double quotes:
Dim Str as string = "<p><img class=""floatLeft"" width=""330"" src=""http://www.com""></p><p>"
来源:https://stackoverflow.com/questions/3691987/why-indexof-returns-always-zero