简体   繁体   English

如何检查字符串是否包含列表值以及是否单独包含列表值和其他值

[英]How to check if string contains list value and separately if contains but with other value

I'm trying to figure out how to define if string contains/does not contains list value and if contains but with other value. 我试图弄清楚如何定义字符串是否包含/不包含列表值以及是否包含但包含其他值。

If I have input string: 如果我输入了字符串:

string inputString = "it was one";

and I want find specific value for condition: 我想找到条件的特定值:

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

But not sure what is a proper way if I want to know also about third condition, if string contains value but also contains other words. 但是,如果我还想了解第三个条件,即字符串是否包含值但还包含其他单词,则不确定什么是正确的方法。

For string: inputString = "it was one"; 对于字符串: inputString = "it was one"; desired result should be: 理想的结果应该是:

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

for string: inputString = "one"; 对于字符串: inputString = "one";

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

and for: inputString = "it was"; 对于: inputString = "it was";

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

I think you are looking for something like this: 我认为您正在寻找这样的东西:

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

You can try an example here 你可以在这里尝试一个例子

why not use below code? 为什么不使用下面的代码? i can not think of one condition where it fails. 我想不出一种失败的条件。

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

find the fiddle here 这里找到小提琴

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

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