C# LastIndexOfAny

来源:百度知道 编辑:UC知道 时间:2024/06/06 15:35:22
我编了一下代码
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string str = "++这是一个综合使用定子串的C#示例++";
int i = str.LastIndexOfAny("++".ToCharArray(),0);
Console.WriteLine(i);
}
}
}
运行结果为
0
但我认为是19,我怀疑我的VS2005有问题,不知道如何解决?

哈哈,结果是没有错,但是 MSDN 的说明 和 VS 里面的提示,都没有讲清楚

LastIndexOfAny 有 3 个 重载,其中, 第二个 和 第三个, 都有一个: int startIndex 这个参数, 解释是 “该搜索从指定字符位置开始”,但是,却没有说明关键的一个地方, 就是:
LastIndexOfAny 是从 字符串的 尾 --> 头 搜索的,也就是逆向搜索,这样效率高, 而这个 startIndex 的值, 表示的是从头到尾的, 所以 你的写法: str.LastIndexOfAny("++".ToCharArray(),0);

表示 从 第一个 + 开始往前搜,但是再往前已经没有了,这个+的位置,就是匹配的结果
int i = str.LastIndexOfAny("++".ToCharArray()); 就会得到你要的结果
int i = str.LastIndexOfAny("++".ToCharArray(), str.Length - 1); 也是你的结果

如果还有疑问,你可以修改 startIndex 的值为 0 ~18 之间的任一个,看结果

貌似没有出错~~看官方MSDN
http://msdn.microsoft.com/zh-cn/vstudio/1d15dfa1(VS.80).aspx

你的VS没有错,可能是我们理解错了。
string str = "++这是一个综合使用定子串的C#示例++";
int i = str.LastIndexOfAny("+".ToCharArray(), 0);
Console.WriteLine(i);
i = str.