[英]Checking if string contains one of the array values using C# .net
i have string[] srt={"t","n","m"}
我有
string[] srt={"t","n","m"}
i need to know if the user input contain one of the values in str and print that value 我需要知道用户输入是否包含str中的值之一并打印该值
i try this code but its not work with me 我尝试使用此代码,但不适用于我
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;
You need to search array for string value you have in str so 您需要在数组中搜索str中具有的字符串值,因此
if (str.Contains(a.ToString()))
Would be 将会
if(a.Contains(s))
Your code would be 您的代码将是
if (a.Contains(str))
{
s = s + "," + a;
}
else
{
s = s + "there is no match in the string";
}
Label1.Text = s;
As a additional note you should use meaning full names instead of a
, s
. 另外要注意的是,您应使用含义全名,而不是
a
, s
。
You can also use conditional operator ?: to make it more simple. 您还可以使用条件运算符?:使其更简单。
string matchResult = a.Contains(s) ? "found" : "not found"
Converting the array to a string isn't what is needed. 不需要将数组转换为字符串。 If you don't care which character matched, use
Any()
如果您不关心匹配哪个字符,请使用
Any()
var s = a.Any(anA => str.Contains(anA))
? "There is a match"
: "There is no match in the string";
And if you want the matches: 如果您想要匹配项:
var matches = a.Where(anA => str.Contains(anA));
var s = matches.Any()
? "These Match: " + string.Join(",", matches)
: "There is no match in the string";
see Checking if a string array contains a value, and if so, getting its position You could use the Array.IndexOf method: 请参见检查字符串数组是否包含值,如果包含,则获取其位置。可以使用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.