2

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;
omania
  • 43
  • 2
  • 8

3 Answers3

3

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"
Adil
  • 146,340
  • 25
  • 209
  • 204
2

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";
StuartLC
  • 104,537
  • 17
  • 209
  • 285
1

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
}
Community
  • 1
  • 1
Jamaxack
  • 2,400
  • 2
  • 24
  • 42