String contains another two strings

前端 未结 17 1545
故里飘歌
故里飘歌 2020-12-15 07:12

Is it possible to have the contain function find if the string contains 2 words or more? This is what I\'m trying to do:

string d = \"You hit someone for 50          


        
相关标签:
17条回答
  • 2020-12-15 07:31

    So you want to know if one string contains two other strings?

    You could use this extension which also allows to specify the comparison:

    public static bool ContainsAll(this string text, StringComparison comparison = StringComparison.CurrentCulture, params string[]parts)
    {
        return parts.All(p => text.IndexOf(p, comparison) > -1);
    }
    

    Use it in this way (you can also omit the StringComparison):

    bool containsAll = d.ContainsAll(StringComparison.OrdinalIgnoreCase, a, b);
    
    0 讨论(0)
  • 2020-12-15 07:33
    string d = "You hit ssomeones for 50 damage";
    string a = "damage";
    string b = "someone";
    
    if (d.Contains(a) && d.Contains(b))
    {
        Response.Write(" " + d);
    
    }
    else
    {
        Response.Write("The required string not contain in d");
    }
    
    0 讨论(0)
  • 2020-12-15 07:34
    public static class StringExtensions
    {
        public static bool Contains(this string s, params string[] predicates)
        {
            return predicates.All(s.Contains);
        }
    }
    
    string d = "You hit someone for 50 damage";
    string a = "damage";
    string b = "someone";
    string c = "you";
    
    if (d.Contains(a, b))
    {
        Console.WriteLine("d contains a and b");
    }
    
    0 讨论(0)
  • 2020-12-15 07:34
        public static bool In(this string str, params string[] p)
        {
            foreach (var s in p)
            {
                if (str.Contains(s)) return true;
            }
            return false;
        }
    
    0 讨论(0)
  • 2020-12-15 07:36

    If you have a list of words you can do a method like this:

    public bool ContainWords(List<string> wordList, string text)
    {
       foreach(string currentWord in wordList)
          if(!text.Contains(currentWord))
             return false;
       return true;
    }
    
    0 讨论(0)
  • 2020-12-15 07:37

    You would be better off just calling Contains twice or making your own extension method to handle this.

    string d = "You hit someone for 50 damage";
    string a = "damage";
    string b = "someone";
    string c = "you";
    
    if(d.Contains(a) && d.Contains(b))
    {
       Console.WriteLine(" " + d);
       Console.ReadLine();
    }
    

    As far as your other question, you could build a regular expression to parse the string to find 50 or if the string is always the same, just split it based on a space and get the 5th part.

    0 讨论(0)
提交回复
热议问题