Flo*_* Gl 41 c# string indexof
有谁知道原因:
" <exception>".LastIndexOf("<",0) returns -1 (wrong)
Run Code Online (Sandbox Code Playgroud)
而
" <exception>".LastIndexOf("<") returns 2 (right)
Run Code Online (Sandbox Code Playgroud)
和
"<exception>".LastIndexOf("<",0) returns 0 (right)
Run Code Online (Sandbox Code Playgroud)
这是一个错误还是我误解了LastIndexOf-Method?
O. *_*per 76
您误解了该LastIndexOf方法的特定重载.
该文档说明如下:
搜索从指定的字符位置开始,然后向后朝向字符串的开头.
请注意,它说backward.因此,如果从位置开始,那个位置或该位置前面0没有"<"子串,因此结果是.-1
相反,如果使用仅占用子字符串的重载,则搜索将从字符串的末尾开始,从而正确地找到指示的子字符串.
Dan*_*iel 10
第二个参数不会像您认为的那样做:
LastIndex(char value, int startIndex)
Run Code Online (Sandbox Code Playgroud)
startIndex是开始向后搜索字符串的char ,所以如果你传递一个0,那么只检查第一个char ...
要从末尾检查整个字符串,您必须传递字符串-1的长度.
文档(http://msdn.microsoft.com/en-us/library/bc3z4t9d.aspx#Y0)说:
搜索从此实例的startIndex字符位置开始,然后向后开始,直到找到任一值或检查了第一个字符位置.例如,如果startIndex是Length - 1,则该方法将搜索字符串中最后一个字符的每个字符到开头.
(我的重点)
所以这:
" <exception>".LastIndexOf("<",0)
Run Code Online (Sandbox Code Playgroud)
从0开始并向后工作,因此正确地找不到结果并返回-1.
我认为混淆是LastIndexOf向后计数,其中IndexOf向前计数.