如何检查字符串是否包含列表值,如果包含但包含其他值,则单独检查

时间:2017-01-02 07:12:03

标签: c# regex string conditional-statements

我正在试图弄清楚如何定义字符串是否包含/不包含列表值,如果包含但是包含其他值。

如果我输入字符串:

string inputString = "it was one";

我希望找到条件的具体值:

var numbList = new List<string> {"zero", "one", "two"}; 

if (!numbList.Any(inputString.Contains)) 
{
     Console.WriteLine("string does not contains list value");                                           
}
else
{
     Console.WriteLine("string contains list value"); 
}

但是如果我想知道第三个条件,如果字符串包含值但是还包含其他单词,那么不确定什么是正确的方法。

对于字符串:inputString = "it was one";所需的结果应为:

 Console.WriteLine("string contains list value and other words"); 

表示字符串:inputString = "one";

 Console.WriteLine("string contains list value"); 

和for:inputString = "it was";

 Console.WriteLine( "string does not contains list value"); 

2 个答案:

答案 0 :(得分:4)

我认为你正在寻找这样的东西:

if (inputString.Split(new string[]{" "},StringSplitOptions.RemoveEmptyEntries).All(x => numbList.Contains(x)))
{
    opDisplay="string contains list value";
}
else if (numbList.Any(x => inputString.Contains(x)))
{
    opDisplay = "string contains list value and other words";
}
else
{
    opDisplay = "string does not contains list value";
}

您可以尝试示例here

答案 1 :(得分:1)

为什么不使用下面的代码?我无法想到失败的一个条件。

            string inputString = "it was one ";
            var numbList = new List<string> { "zero", "one", "two" };
            if (numbList.Any(x => inputString.Contains(x)))
            {
                if (numbList.Any(x => inputString.Trim().StartsWith(x) && inputString.Trim().EndsWith(x)))
                {
                    Console.WriteLine("string contains list value");
                }
                else
                {
                    Console.WriteLine("string contains list value and other words");
                }
            }
            else
            {
                Console.WriteLine("string does not contains list value");
            }

找到小提琴here