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
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));
}
Because b + a ="someonedamage"
, try this to achieve :
if (d.Contains(b) && d.Contains(a))
{
Console.WriteLine(" " + d);
Console.ReadLine();
}
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);
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.
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));
}
}
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))