Home Articles

使用C#检查字符串是否包含字符串数组中的字符串

Asked
Viewed 460 times
222

我想使用C#来检查字符串值是否包含字符串数组中的单词 . 例如,

string stringToCheck = "text1text2text3";

string[] stringArray = { "text1", "someothertext", etc... };

if(stringToCheck.contains stringArray) //one of the items?
{

}

如何检查'stringToCheck'的字符串值是否包含数组中的单词?

26 Answers

  • 711

    试试这个:

    无需使用LINQ

    if (Array.IndexOf(array, Value) >= 0)
    {
        //Your stuff goes here
    }
    
  • 115

    使用Linq和方法组将是最快速,更紧凑的方法 .

    var arrayA = new[] {"element1", "element2"};
    var arrayB = new[] {"element2", "element3"};
    if (arrayB.Any(arrayA.Contains)) return true;
    
  • 32

    如果 stringArray 包含大量不同长度的字符串,请考虑使用Trie来存储和搜索字符串数组 .

    public static class Extensions
    {
        public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
        {
            Trie trie = new Trie(stringArray);
            for (int i = 0; i < stringToCheck.Length; ++i)
            {
                if (trie.MatchesPrefix(stringToCheck.Substring(i)))
                {
                    return true;
                }
            }
    
            return false;
        }
    }
    

    这是 Trie 类的实现

    public class Trie
    {
        public Trie(IEnumerable<string> words)
        {
            Root = new Node { Letter = '\0' };
            foreach (string word in words)
            {
                this.Insert(word);
            }
        }
    
        public bool MatchesPrefix(string sentence)
        {
            if (sentence == null)
            {
                return false;
            }
    
            Node current = Root;
            foreach (char letter in sentence)
            {
                if (current.Links.ContainsKey(letter))
                {
                    current = current.Links[letter];
                    if (current.IsWord)
                    {
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
    
            return false;
        }
    
        private void Insert(string word)
        {
            if (word == null)
            {
                throw new ArgumentNullException();
            }
    
            Node current = Root;
            foreach (char letter in word)
            {
                if (current.Links.ContainsKey(letter))
                {
                    current = current.Links[letter];
                }
                else
                {
                    Node newNode = new Node { Letter = letter };
                    current.Links.Add(letter, newNode);
                    current = newNode;
                }
            }
    
            current.IsWord = true;
        }
    
        private class Node
        {
            public char Letter;
            public SortedList<char, Node> Links = new SortedList<char, Node>();
            public bool IsWord;
        }
    
        private Node Root;
    }
    

    如果 stringArray 中的所有字符串具有相同的长度,那么最好只使用 HashSet 而不是 Trie

    public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
    {
        int stringLength = stringArray.First().Length;
        HashSet<string> stringSet = new HashSet<string>(stringArray);
        for (int i = 0; i < stringToCheck.Length - stringLength; ++i)
        {
            if (stringSet.Contains(stringToCheck.Substring(i, stringLength)))
            {
                return true;
            }
        }
    
        return false;
    }
    
  • 27
    int result = Array.BinarySearch(list.ToArray(), typedString, StringComparer.OrdinalIgnoreCase);
    
  • 7

    我使用以下代码检查字符串是否包含字符串数组中的任何项:

    foreach (string s in stringArray)
    {
        if (s != "")
        {
            if (stringToCheck.Contains(s))
            {
                Text = "matched";
            }
        }
    }
    
  • 5

    试试这个

    string stringToCheck = "text1text2text3";
    string[] stringArray = new string[] { "text1" };
    
    var t = lines.ToList().Find(c => c.Contains(stringToCheck));
    

    它将返回您正在查找的文本的第一个出处的行 .

  • 3

    最简单和样本方式 .

    bool bol=Array.Exists(stringarray,E => E == stringtocheck);
    
  • 3

    我会使用Linq但它仍然可以通过以下方式完成:

    new[] {"text1", "text2", "etc"}.Contains(ItemToFind);
    
  • 1

    这是你如何做到的:

    string stringToCheck = "text1";
    string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
    foreach (string x in stringArray)
    {
        if (stringToCheck.Contains(x))
        {
            // Process...
        }
    }
    

    UPDATE: 您可能正在寻找更好的解决方案..请参阅下面的@Anton Gogolev的答案,其中使用了LINQ .

  • 1

    也许这样的东西:

    string stringToCheck = "text1text2text3";
    string[] stringArray = new string[] { "text1" };
    if (Array.Exists<string>(stringArray, (Predicate<string>)delegate(string s) { 
        return stringToCheck.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1; })) {
        Console.WriteLine("Found!");
    }
    
  • 1

    尝试:

    String[] val = { "helloword1", "orange", "grape", "pear" };
    String sep = "";
    string stringToCheck = "word1";
    
    bool match = String.Join(sep,val).Contains(stringToCheck);
    bool anothermatch = val.Any(s => s.Contains(stringToCheck));
    
  • 1

    你也可以像Anton Gogolev建议的那样做,检查 stringArray1 中的 any item 是否与 stringArray2 中的 any item 匹配:

    if(stringArray1.Any(stringArray2.Contains))
    

    同样,stringArray1中的 all items 与stringArray2中的 all items 匹配:

    if(stringArray1.All(stringArray2.Contains))
    
  • 1

    简单的解决方案,不需要linq任何

    String.Join(“,”,array).Contains(Value“,”);

  • 0

    这是如何做:

    if(stringArray.Any(stringToCheck.Contains))
    /* or a bit longer: (stringArray.Any(s => stringToCheck.Contains(s))) */
    

    这将检查 stringToCheck 是否包含 stringArray 中的任何一个子字符串 . 如果要确保它包含所有子字符串,请将 Any 更改为 All

    if(stringArray.All(stringToCheck.Contains))
    
  • 0

    只需使用linq方法:

    stringArray.Contains(stringToCheck)
    

    (抱歉无法在现有答案上添加评论,因为我的声誉<50)

  • 0
    string strName = "vernie";
    string[] strNamesArray = { "roger", "vernie", "joel" };
    
    if (strNamesArray.Any(x => x == strName))
    {
       // do some action here if true...
    }
    
  • 0

    您可以定义自己的 string.ContainsAny()string.ContainsAll() 方法 . 作为奖励,我甚至抛出了一个允许不区分大小写的比较等的 string.Contains() 方法 .

    public static class Extensions
    {
        public static bool Contains(this string source, string value, StringComparison comp)
        {
            return source.IndexOf(value, comp) > -1;
        }
    
        public static bool ContainsAny(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
        {
            return values.Any(value => source.Contains(value, comp));
        }
    
        public static bool ContainsAll(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
        {
            return values.All(value => source.Contains(value, comp));
        }
    }
    

    您可以使用以下代码测试这些:

    public static void TestExtensions()
        {
            string[] searchTerms = { "FOO", "BAR" };
            string[] documents = {
                "Hello foo bar",
                "Hello foo",
                "Hello"
            };
    
            foreach (var document in documents)
            {
                Console.WriteLine("Testing: {0}", document);
                Console.WriteLine("ContainsAny: {0}", document.ContainsAny(searchTerms, StringComparison.OrdinalIgnoreCase));
                Console.WriteLine("ContainsAll: {0}", document.ContainsAll(searchTerms, StringComparison.OrdinalIgnoreCase));
                Console.WriteLine();
            }
        }
    
  • 0

    试试这个,这里的示例:检查字段是否包含数组中的任何单词 . 检查字段(someField)是否包含数组中的任何单词 .

    String[] val = { "helloword1", "orange", "grape", "pear" };   
    
    Expression<Func<Item, bool>> someFieldFilter = i => true;
    
    someFieldFilter = i => val.Any(s => i.someField.Contains(s));
    
  • 0
    public bool ContainAnyOf(string word, string[] array) 
        {
            for (int i = 0; i < array.Length; i++)
            {
                if (word.Contains(array[i]))
                {
                    return true;
                }
            }
            return false;
        }
    
  • 0

    我使用了与Maitrey684的IndexOf类似的方法和Theomax的foreach循环来创建它 . (注意:前3个“字符串”行只是一个如何创建数组并使其成为正确格式的示例) .

    如果要比较2个数组,它们将以分号分隔,但最后一个值后面没有一个数组 . 如果在数组的字符串形式中附加一个分号(即a; b; c变为a; b; c;),则可以使用“x;”匹配无论它处于什么位置:

    bool found = false;
    string someString = "a-b-c";
    string[] arrString = someString.Split('-');
    string myStringArray = arrString.ToString() + ";";
    
    foreach (string s in otherArray)
    {
        if (myStringArray.IndexOf(s + ";") != -1) {
           found = true;
           break;
        }
    }
    
    if (found == true) { 
        // ....
    }
    
  • 0

    试试这个,不需要循环..

    string stringToCheck = "text1";
    List<string> stringList = new List<string>() { "text1", "someothertext", "etc.." };
    if (stringList.Exists(o => stringToCheck.Contains(o)))
    {
    
    }
    
  • 0

    要完成上述答案,请 IgnoreCase 检查使用:

    stringArray.Any(s => stringToCheck.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) > -1)
    
  • 0

    就我而言,上述答案无效 . 我正在检查数组中的字符串并将其分配给布尔值 . 我修改了@Anton Gogolev的答案并删除了 Any() 方法并将 stringToCheck 放在 Contains() 方法中 .

    bool = stringArray.Contains(stringToCheck);
    
  • 0

    展示了三种选择 . 我更愿意发现第三个是最简洁的 .

    class Program {
        static void Main(string[] args) {
        string req = "PUT";
        if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
            Console.WriteLine("one.1.A");  // IS TRUE
        }
        req = "XPUT";
        if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
            Console.WriteLine("one.1.B"); // IS TRUE
        }
        req = "PUTX";
        if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
            Console.WriteLine("one.1.C");  // IS TRUE
        }
        req = "UT";
        if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
            Console.WriteLine("one.1.D"); // false
        }
        req = "PU";
        if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
            Console.WriteLine("one.1.E"); // false
        }
        req = "POST";
        if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
            Console.WriteLine("two.1.A"); // IS TRUE
        }
        req = "ASD";
        if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
            Console.WriteLine("three.1.A");  // false
        }
    
    
        Console.WriteLine("-----");
        req = "PUT";
        if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
            Console.WriteLine("one.2.A"); // IS TRUE
        }
        req = "XPUT";
        if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
            Console.WriteLine("one.2.B"); // false
        }
        req = "PUTX";
        if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
            Console.WriteLine("one.2.C"); // false
        }
        req = "UT";
        if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
            Console.WriteLine("one.2.D"); // false
        }
        req = "PU";
        if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
            Console.WriteLine("one.2.E"); // false
        }
        req = "POST";
        if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
            Console.WriteLine("two.2.A");  // IS TRUE
        }
        req = "ASD";
        if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
            Console.WriteLine("three.2.A");  // false
        }
    
        Console.WriteLine("-----");
        req = "PUT";
        if ((new string[] {"PUT", "POST"}.Contains(req)))  {
            Console.WriteLine("one.3.A"); // IS TRUE
        }
        req = "XPUT";
        if ((new string[] {"PUT", "POST"}.Contains(req)))  {
            Console.WriteLine("one.3.B");  // false
        }
        req = "PUTX";
        if ((new string[] {"PUT", "POST"}.Contains(req)))  {
            Console.WriteLine("one.3.C");  // false
        }
        req = "UT";
        if ((new string[] {"PUT", "POST"}.Contains(req)))  {
            Console.WriteLine("one.3.D");  // false
        }
        req = "PU";
        if ((new string[] {"PUT", "POST"}.Contains(req)))  {
            Console.WriteLine("one.3.E");  // false
        }
        req = "POST";
        if ((new string[] {"PUT", "POST"}.Contains(req)))  {
            Console.WriteLine("two.3.A");  // IS TRUE
        }
        req = "ASD";
        if ((new string[] {"PUT", "POST"}.Contains(req)))  {
            Console.WriteLine("three.3.A");  // false
        }
    
        Console.ReadKey();
        }
    }
    
  • -1

    我在控制台应用程序中使用以下内容来检查参数

    var sendmail = args.Any( o => o.ToLower() == "/sendmail=true");
    
  • -1
    string [] lines = {"text1", "text2", "etc"};
    
    bool bFound = lines.Any(x => x == "Your string to be searched");
    

    如果搜索的字符串与数组'lines'的任何元素匹配,则bFound设置为true .

Related