如何高效地判断一个字符串中是否包含某字符串速度要很快

解决方案 »

  1.   

    String.Contains(...) .net 2.0
      

  2.   

    string s = "abcd";
    if (s!=null && s.Length>0 && s.Replace("ab","").Length<s.Length)
    {
       //...
    }测一下吧
      

  3.   

    为什么要比IndexOf快呢?
    如果正则或间接方法快,那么微软为什么不优化该方法呢?不可理解。鄙人认为,用IndexOf就可以了,应该比那些方法快。
      

  4.   

    用正则有优点如下:
    1. 速度快,这个不用多说
    2. 灵活比如我想要在一个字符串中判断是否包含 "a***bc"这样的字符串(*代表任意字符),正则可以容易地办到,IndexOf方法可以吗?
      

  5.   

    那只能说明正则用法比较灵活,在灵活方面,indexof自然没有正则强大。
    但是楼主说的是“高效地判断一个字符串中是否包含某字符串”,是包含,所以正则的优点并没有用上。
    而IndexOf用法单一,就是判断一字符串中是否有另一字符串(等。。)功能,简单方便直接,如果单一功能的效率都比多功能的效率还低,还要这个方法干吗?要这个方法还有意义吗?为什么不优化呢?
    (我这么说,是在信任C#语言的设计的基础上说的,当然不排除C#语言设计的垃圾之处。)
      

  6.   

    多关键字搜索的例子:
    http://www.dotnetjunkies.com/Tutorial/195E323C-78F3-4884-A5AA-3A1081AC3B35.dcik
      

  7.   

    indexof未必比正则快,测试程序如下:1. 测试indexof, 循环100000次
    private void button1_Click(object sender, System.EventArgs e)
    {
    String str1 = "Beginning with Windows 95 and Windows NT&#174; 4.0, Input Method Editors (IMEs) are provided as a dynamic-link library (DLL), in contrast to the IMEs for the Windows 3.1 Far East Edition. Each IME runs as one of the multilingual keyboard layouts. In comparison to the Windows 3.1 IME, the new Win32 Multilingual Input Method Manager (IMM) and Input Method Editor (IME) architecture provide the following advantages: Run as a component of the multilingual environment";
    String str2 = "dynamic-link";
    bool flag = false;
    long t1 = System.Environment.TickCount;
    for (int i = 0; i < 100000; i++)
    {
    if (str1.IndexOf(str2) > -1)
    {
    flag = true;
    }
    }
    long t2 = System.Environment.TickCount;
    long t3 = t2 - t1;
    MessageBox.Show(t3.ToString());
    MessageBox.Show(flag.ToString());
    }
    2. 测试正则, 循环100000次
    private void button2_Click(object sender, System.EventArgs e)
    {
    String str1 = "Beginning with Windows 95 and Windows NT&#174; 4.0, Input Method Editors (IMEs) are provided as a dynamic-link library (DLL), in contrast to the IMEs for the Windows 3.1 Far East Edition. Each IME runs as one of the multilingual keyboard layouts. In comparison to the Windows 3.1 IME, the new Win32 Multilingual Input Method Manager (IMM) and Input Method Editor (IME) architecture provide the following advantages: Run as a component of the multilingual environment";
    String str2 = "dynamic-link";
    bool FoundMatch = false;
    long t1 = System.Environment.TickCount;
    for (int i = 0; i < 100000; i++)
    {
    try 
    {
    FoundMatch = Regex.IsMatch(str1, str2);

    catch (ArgumentException ex) 
    {
    // Syntax error in the regular expression
    }
    }
    long t2 = System.Environment.TickCount;
    long t3 = t2 - t1;
    MessageBox.Show(t3.ToString());
    MessageBox.Show(FoundMatch.ToString());
    }
    测试结果,indexof稍慢, 不知道我上面的测试方法有没有错,大家看看