简体   繁体   English

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

[英]Using C# to check if string contains a string in string array

I want to use C# to check if a string value contains a word in a string array.我想使用 C# 检查字符串值是否包含字符串数组中的单词。 For example,例如,

string stringToCheck = "text1text2text3";

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

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

}

How can I check if the string value for 'stringToCheck' contains a word in the array?如何检查“stringToCheck”的字符串值是否包含数组中的单词?

Here's how:就是这样:

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

here is how you can do it:这是你可以做到的:

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

Try this:试试这个:

No need to use LINQ无需使用 LINQ

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

只需使用 linq 方法:

stringArray.Contains(stringToCheck)
string strName = "vernie";
string[] strNamesArray = { "roger", "vernie", "joel" };

if (strNamesArray.Any(x => x == strName))
{
   // do some action here if true...
}

最简单的示例方式。

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

Something like this perhaps:可能是这样的:

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!");
}
stringArray.ToList().Contains(stringToCheck)

Using Linq and method group would be the quickest and more compact way of doing this.使用 Linq 和方法组将是最快和更紧凑的方法。

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

You can define your own string.ContainsAny()<\/code> and string.ContainsAll()<\/code> methods.您可以定义自己的string.ContainsAny()<\/code>和string.ContainsAll()<\/code>方法。 As a bonus, I've even thrown in a string.Contains()<\/code> method that allows for case-insensitive comparison, etc.作为奖励,我什至string.Contains()<\/code>了string.Contains()<\/code>方法,该方法允许进行不区分大小写的比较等。

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));
    }
}

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

var sendmail = args.Any( o => o.ToLower() == "/sendmail=true");

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

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

Most of those solution is correct, but if You need check values without case sensitivity这些解决方案中的大多数都是正确的,但是如果您需要不区分大小写的检查值

using System.Linq;
...
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext"};

if(stringArray.Any(a=> String.Equals(a, stringToCheck, StringComparison.InvariantCultureIgnoreCase)) )
{ 
   //contains
}

if (stringArray.Any(w=> w.IndexOf(stringToCheck, StringComparison.InvariantCultureIgnoreCase)>=0))
{
   //contains
}

You can try this solution as well.您也可以尝试此解决方案。

string[] nonSupportedExt = { ".3gp", ".avi", ".opus", ".wma", ".wav", ".m4a", ".ac3", ".aac", ".aiff" };
        
bool valid = Array.Exists(nonSupportedExt,E => E == ".Aac".ToLower());

You can also do the same thing as Anton Gogolev suggests to check if any item<\/strong> in stringArray1<\/code> matches any item<\/strong> in stringArray2<\/code> :你也可以做同样的事情,安东Gogolev建议检查是否在任何项目<\/strong>stringArray1<\/code>在任何一个项目<\/strong>匹配stringArray2<\/code> :

if(stringArray1.Any(stringArray2.Contains))

Try:尝试:

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));

If stringArray contains a large number of varied length strings, consider using a Trie to store and search the string array.如果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;
    }
}

Here is the implementation of the Trie class下面是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;
}

If all strings in stringArray have the same length, you will be better off just using a HashSet instead of a Trie如果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;
}

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

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

For my case, the above answers did not work.就我而言,上述答案不起作用。 I was checking for a string in an array and assigning it to a boolean value.我正在检查数组中的字符串并将其分配给布尔值。 I modified @Anton Gogolev's answer and removed the Any() method and put the stringToCheck inside the Contains() method.我修改了@Anton Gogolev 的答案并删除了Any()方法并将stringToCheck放在Contains()方法中。

bool isContain = stringArray.Contains(stringToCheck);

LINQ: LINQ:

arrray.Any(x => word.Equals(x)); arrray.Any(x => word.Equals(x));

This is to see if array contains the word (exact match).这是为了查看数组是否包含单词(完全匹配)。 Use.Contains for the substring, or whatever other logic you may need to apply instead. Use.Contains 用于 substring,或您可能需要应用的任何其他逻辑。

public bool ContainAnyOf(string word, string[] array) 
    {
        for (int i = 0; i < array.Length; i++)
        {
            if (word.Contains(array[i]))
            {
                return true;
            }
        }
        return false;
    }

I used a similar method to the IndexOf by Maitrey684 and the foreach loop of Theomax to create this.我使用了与 Maitrey684 的 IndexOf 和 Theomax 的 foreach 循环类似的方法来创建它。 (Note: the first 3 "string" lines are just an example of how you could create an array and get it into the proper format). (注意:前 3 行“字符串”只是说明如何创建数组并将其转换为正确格式的示例)。

If you want to compare 2 arrays, they will be semi-colon delimited, but the last value won't have one after it.如果要比较 2 个数组,它们将以分号分隔,但最后一个值后面不会有一个。 If you append a semi-colon to the string form of the array (ie a;b;c becomes a;b;c;), you can match using "x;"如果在数组的字符串形式后附加分号(即 a;b;c 变为 a;b;c;),则可以使用“x;”进行匹配no matter what position it is in:不管它在什么位置:

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) { 
    // ....
}
string [] lines = {"text1", "text2", "etc"};

bool bFound = lines.Any(x => x == "Your string to be searched");

Try this试试这个

string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };

var t = lines.ToList().Find(c => c.Contains(stringToCheck));

Simple solution, not required linq any简单的解决方案,不需要 linq 任何

String.Join(",", array).Contains(Value+","); String.Join(",", 数组).Contains(Value+",");

int result = Array.BinarySearch(list.ToArray(), typedString, StringComparer.OrdinalIgnoreCase);

Try this, no need for a loop..试试这个,不需要循环..

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

}

try this, here the example : To check if the field contains any of the words in the array.试试这个,这里是例子:检查字段是否包含数组中的任何单词。 To check if the field(someField) contains any of the words in the array.检查字段(someField)是否包含数组中的任何单词。

String[] val = { "helloword1", "orange", "grape", "pear" };   

Expression<Func<Item, bool>> someFieldFilter = i => true;

someFieldFilter = i => val.Any(s => i.someField.Contains(s));

I used the following code to check if the string contained any of the items in the string array:我使用以下代码检查字符串是否包含字符串数组中的任何项:

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

Three options demonstrated.展示了三个选项。 I prefer to find the third as the most concise.我更喜欢找到第三个最简洁的。

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM