简体   繁体   中英

String contains more than one word

In my project I'm having a StringBuilder which takes the selected value of dropdown lists.

StringBuilder builder = new StringBuilder();
builder.Append(ddl_model.SelectedValue);
builder.Append(ddl_language.SelectedValue);

foreach (string str in list)
{
    if (str.Contains(builder.ToString()))
    {
        lstpdfList.Items.Add(str);
    }
}

It works with one value. I would like to make that I can check if contains two or more words.

I have a file like PM12_Manual_Rev1_EN . Now I can find if it contains PM12. But there is a lot of them. So I would like to check if contains PM12 + EN.

1) Don't call builder.ToString() inside the foreach, it will rebuild the string everytime, and it defeats the performance purpose of StringBuilder.

2) Don't use a StringBuilder, use a List in which you store the words you want to match for, if each selected value may contain several words, split them:

var keywords = new List<string>();
keywords.AddRange(ddl_model.SelectedValue.Split(' '));
keywords.AddRange(ddl_language.SelectedValue.Split(' '));

foreach(string str in list)
   if (keywords.Any(keyword => str.Contains(keyword))
      lstpdfList.Items.Add(str);

You could use regexes .

    string testString ="PM12_Manual_Rev1_EN";       

    var wordRegex = new Regex( "PM12.*EN", RegexOptions.IgnoreCase );

    if (wordRegex.IsMatch( testString ))
    {
        Console.WriteLine("we've found multiple matches, REGEX edition");       
    }

Or you could use Contains with Linq like this:

    string testString ="PM12_Manual_Rev1_EN";

    var checkWords = new List<String>() {"PM12", "EN"};
    if(checkWords.All(w => testString.Contains(w)))
    {
        Console.WriteLine("we've found multiple matches");      
    }

You should use String.Contains Method, its the easiest way! It returns a value indicating whether the specified String object occurs within this string.

@Shaks has right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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