【问题标题】:Check a string for containing a list of substrings检查字符串是否包含子字符串列表
【发布时间】:2011-11-29 13:35:55
【问题描述】:

如何检查特定字符串以查看它是否包含一系列子字符串? 具体是这样的:

public GetByValue(string testString) {

    // if testString contains these substrings I want to throw back that string was invalid
    // string cannot contain "the " or any part of the words "College" or "University"

   ...
}

【问题讨论】:

  • 取决于您如何看待未来的发展。正则表达式可能是一个好的开始。你有没有尝试过?
  • 不确定从哪里开始...我的数据访问层正在使用输入的字符串进行搜索...如果字符串包含“the”或“college”或“大学”——例如:“col”或“uni”——那么返回的行太多,太通用了。至于成长,我只关心这三个字。我在 DAL 中使用 Linq to SQL

标签: c#-4.0


【解决方案1】:

如果性能是一个问题,您可能需要考虑使用RegexStringValidator class

【讨论】:

    【解决方案2】:

    你可以使用 string.Contains() 方法

    http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

    // This example demonstrates the String.Contains() method
    using System;
    
    class Sample 
    {
    public static void Main() 
    {
    string s1 = "The quick brown fox jumps over the lazy dog";
    string s2 = "fox";
    bool b;
    b = s1.Contains(s2);
    Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b);
    }
    

    } /* 此示例产生以下结果:

    字符串 s2 是否在字符串 s1 中?:真 */

    【讨论】:

      【解决方案3】:

      这是一个有趣的问题。正如@Jon 提到的,正则表达式可能是一个好的开始,因为它允许您一次(可能)评估多个否定匹配。相比之下,简单的循环效率会低得多。

      【讨论】:

        【解决方案4】:

        您可以按如下方式检查....

           class Program
        {
        
        
        
        public static bool checkstr(string str1,string str2)
        {
         bool c1=str1.Contains(str2);
         return c1;
        

        }

        public static void Main()
        {
        string st = "I am a boy";
        string st1 = "boy";
        
        bool c1=checkstr(st,st1);
        //if st1 is in st then it print true otherwise false
              System.Console.WriteLine(c1);
        }
        }
        

        【讨论】:

          【解决方案5】:

          决定不检查字符串以限制我的数据返回,而是将我的返回限制为 .Take(15),如果返回计数超过 65,536,则返回 null

          【讨论】:

            猜你喜欢
            • 2011-11-09
            • 2013-05-18
            • 2021-12-20
            • 1970-01-01
            • 1970-01-01
            • 2014-11-22
            • 2013-02-05
            • 2021-12-14
            • 2015-07-27
            相关资源
            最近更新 更多