繁体   English   中英

使用C#.net检查字符串是否包含数组值之一

[英]Checking if string contains one of the array values using C# .net

我有string[] srt={"t","n","m"}

我需要知道用户输入是否包含str中的值之一并打印该值

我尝试使用此代码,但不适用于我

 string str = Textbox.Text; string s = ""; string[] a = {"m","t","n"}; if (str.Contains(a.ToString())) { s = s + a; } else { s = s + "there is no match in the string"; } Label1.Text = s; 

您需要在数组中搜索str中具有的字符串值,因此

if (str.Contains(a.ToString()))

将会

if(a.Contains(s))

您的代码将是

if (a.Contains(str))
{
    s = s + "," + a;
}
else
{
     s = s + "there is no match in the string";
}

Label1.Text = s;

另外要注意的是,您应使用含义全名,而不是as

您还可以使用条件运算符?:使其更简单。

string matchResult = a.Contains(s) ? "found" : "not found"

不需要将数组转换为字符串。 如果您不关心匹配哪个字符,请使用Any()

var s = a.Any(anA => str.Contains(anA))
    ? "There is a match"
    : "There is no match in the string";

如果您想要匹配项:

var matches = a.Where(anA => str.Contains(anA));
var s = matches.Any()
    ? "These Match: " + string.Join(",", matches)
    : "There is no match in the string";

请参见检查字符串数组是否包含值,如果包含,则获取其位置。可以使用Array.IndexOf方法:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos >- 1)
{
    // the array contains the string and the pos variable
    // will have its position in the array
}

暂无
暂无

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

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