[c#] String contains another two strings

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 damage";
string a = "damage";
string b = "someone";
string c = "you";

if(d.Contains(b + a))
{   
    Console.WriteLine(" " + d);
    Console.ReadLine();
}

When I run this, the console window just shuts down really fast without showing anything.

And another question: if I for one want to add how much damage is done, what would be the easiest way to get that number and get it into a TryParse?

This question is related to c# string contains

The answer is


That is because the if statements returns false since d doesn't contain b + a i.e "someonedamage"


Because b + a ="someonedamage", try this to achieve :

if (d.Contains(b) && d.Contains(a))
{  
    Console.WriteLine(" " + d);
    Console.ReadLine();
}

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

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

 class Program {
          static void Main(String[] args) {
             // By using extension methods
             if ( "Hello world".ContainsAll(StringComparison.CurrentCultureIgnoreCase, "Hello", "world") ) 
                Console.WriteLine("Found everything by using an extension method!");
             else 
                Console.WriteLine("I didn't");

             // By using a single method
             if ( ContainsAll("Hello world", StringComparison.CurrentCultureIgnoreCase, "Hello", "world") )
                Console.WriteLine("Found everything by using an ad hoc procedure!");
             else 
                Console.WriteLine("I didn't");

          }

          private static Boolean ContainsAll(String str, StringComparison comparisonType, params String[] values) {
             return values.All(s => s.Equals(s, comparisonType));
          }    
       }

       // Extension method for your convenience
       internal static class Extensiones {
          public static Boolean ContainsAll(this String str, StringComparison comparisonType, params String[] values) {
             return values.All(s => s.Equals(s, comparisonType));
          }
       }

    public static bool In(this string str, params string[] p)
    {
        foreach (var s in p)
        {
            if (str.Contains(s)) return true;
        }
        return false;
    }

Your b + a is equal "someonedamage", since your d doesn't contain that string, your if statement returns false and doesn't run following parts.

Console.WriteLine(" " + d);
Console.ReadLine();

You can control this more efficient as;

bool b = d.Contains(a) && d.Contains(b);

Here is a DEMO.


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

Are you looking for the string contains a certain number of words or contains specific words? Your example leads towards the latter.

In that case, you may wish to look into parsing strings or at least use regex.
Learn regex - it will be useful 1000x over in programming. I cannot emphasize this too much. Using contains and if statements will turn into a mess very quickly.

If you are just trying to count words, then :

string d = "You hit someone for 50 damage";  
string[] words = d.Split(' ');  // Break up the string into words
Console.Write(words.Length);  

This is because d does not contain b + a (i.e. "someonedamage"), and therefore the application just terminates (since your Console.ReadLine(); is within the if block).


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

You could write an extension method with linq.

public static bool MyContains(this string str, params string[] p) {
 return !p.Cast<string>().Where(s => !str.Contains(s)).Any();
}

EDIT (thx to sirid):

public static bool MyContains(this string str, params string[] p) {
 return !p.Any(s => !str.Contains(s));
}

With the code d.Contains(b + a) you check if "You hit someone for 50 damage" contains "someonedamage". And this (i guess) you don't want.

The + concats the two string of b and a.

You have to check it by

if(d.Contains(b) && d.Contains(a))

I just checked for a space in contains to check if the string has 2 or more words.

string d = "You hit someone for 50 damage";
string a = "damage";
string b = "someone";
string c = "you";

bool a = ?(d.contains(" ")):true:false;

if(a)
{
 Console.WriteLine(" " + d);
}

Console.Read();

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

So what is that you are really after? If you want to make sure that something has hit for damage (in this case), why are you not using string.Format

string a = string.Format("You hit someone for {d} damage", damage);

In this way, you have the ability to have the damage qualifier that you are looking for, and are able to calculate that for other parts.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to contains

Check if element is in the list (contains) Excel formula to search if all cells in a range read "True", if not, then show "False" How to use regex in XPath "contains" function R - test if first occurrence of string1 is followed by string2 Java List.contains(Object with field value equal to x) Check if list contains element that contains a string and get that element Search for "does-not-contain" on a DataFrame in pandas String contains another two strings Java - Opposite of .contains (does not contain) String contains - ignore case