你是否被C#/.Net的LastIndexOf 和 LastIndexOfAny 雷到过呢?

周末了,起得晚。爬起来,洗漱完毕打开电脑,习惯性的收MAIL,第一封就吸引了我,标题:

老兄,我发现了.NET里面string.LastIndexOfAny的一个逻辑性错误的BUG

我的第一反应: 这位兄弟又joking了 ,打开正文,一段再简单不过的代码:

string str = "+-这是一个综合使用确定子串位置的C#示例+-";

int iLastPos = str.LastIndexOfAny("+-".ToCharArray(), 0);
Console.WriteLine(iLastPos);

Console.ReadKey(true);
最后是问我,结果等于多少, 为什么?

我看了一下,然后就想当然的认为,这也太简单了,不就是最后一位嘛, str.Length – 1 呗! 不过,为了表示对这位兄弟的尊重,我还是运行了一下这个代码,显示的结果,让我大为surprise: 0

Why?   ,查之!!

LastIndexOfAny
报告在 Unicode 数组中指定的一个或多个字符在此实例中的最后一个匹配项的索引位置
Reports the index position of the last occurrence in this instance of one or more characters specified in a Unicode array.


重载1: String.LastIndexOfAny(char[] anyOf)
-------------------------------------------------------------------
参数
anyOf
    Unicode 字符数组,包含一个或多个要查找的字符。 
    A Unicode character array containing one or more characters to seek.

重载2:String.LastIndexOfAny ( char[] anyOf,  int startIndex)
------------------------------------------------------------------------------------
参数
anyOf
    Unicode 字符数组,包含一个或多个要查找的字符。 
   A Unicode character array containing one or more characters to seek. 

startIndex
    搜索起始位置。 
    The search starting position.

重载3: 和2类似,我就略掉了

返回值
此实例中最后一个匹配项的索引位置,在此位置找到 anyOf 中的任意字符;否则,如果未找到 anyOf 中的字符,则为 -1。
The index position of the last occurrence in this instance where any character in anyOf was found; otherwise, -1 if no character in anyOf was found.

备注

索引编号从零开始。
此方法从此实例的 startIndex 字符位置开始,从后向前进行搜索,直到找到 anyOf 中的一个字符或检查到第一个字符位置。该搜索区分大小写。
Index numbering starts from zero.
This method begins searching at the last character position of this instance and proceeds backward toward the beginning until either a character in anyOf is found or the first character position has been examined. The search is case-sensitive.

我上面加红的地方,是关键点,因为是 求LAST,所以逆向效率高,这是无可厚非的,问题就出在这里了,逆向搜索

重载2中,对startIndex 这个参数的说明是

startIndex
    搜索起始位置。 
    The search starting position

这就是说startIndex 是按正向的顺序来表示的,那就一目了然了,回到最初的问题:

string str = "+-这是一个综合使用确定子串位置的C#示例+-";

int iLastPos = str.LastIndexOfAny("+-".ToCharArray(), 0);
Console.WriteLine(iLastPos);

Console.ReadKey(true);

上面的代码中, 将 startIndex 设置为 0, 他的本意是搜索整个字符串!

但是因为 LastIndexOfAny 是逆向搜索的, 结果就成了 从 第一个 字符开始,向搜索,结果就是匹配了第一个字符,返回了 0

如果要搜索整个字符串,正确的写法是

string str = "+-这是一个综合使用确定子串位置的C#示例+-";

int iLastPos = str.LastIndexOfAny("+-".ToCharArray(), str.Length - 1);
Console.WriteLine(iLastPos);

Console.ReadKey(true);

 

其实,如果看过 MSDN 上,关于 LastIndexOfAny 的那个sample的话,就一目了然了

LastIndexOf 和 LastIndexOfAny 是一样的逻辑,就不重复了

posted @ 2009-02-28 19:11  三角猫  阅读(4098)  评论(12编辑  收藏  举报