有谁知道为什么:
" <exception>".LastIndexOf("<",0) returns -1 (wrong)
同时
" <exception>".LastIndexOf("<") returns 2 (right)
和
"<exception>".LastIndexOf("<",0) returns 0 (right)
这是错误还是我误解了 LastIndexOf 方法?
最佳答案
您误解了 LastIndexOf
的特定重载方法。
docs说明如下:
The search starts at a specified character position and proceeds backward toward the beginning of the string.
请注意它说 backward
.所以,如果你从位置 0
开始, 没有 "<"
该位置的子字符串或该位置的前面,因此结果为 -1
.
相反,如果您使用只接受子字符串的重载,搜索将从字符串的末尾开始,因此可以正确找到指定的子字符串。
关于c# - string.LastIndexOf() 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12421160/