问题描述:

i have string[] srt={"t","n","m"}

i need to know if the user input contain one of the values in str and print that value

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

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.

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

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:

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
}
相关阅读:
Top