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;

4
  • the sippet doesn't run!! Commented Feb 17, 2015 at 5:13
  • The question is a bit confusing, because it seems to be the user input will be in str, so it seems you are trying to check if the user input contains something from a, correct? Commented Feb 17, 2015 at 5:15
  • possible duplicate of Using C# to check if string contains a string in string array Commented Feb 17, 2015 at 5:16
  • YES THAT WHAT I WANT TO DO Commented Feb 17, 2015 at 5:35

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.