String contains another two strings
Asked Answered
J

17

16

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?

Jamestown answered 16/4, 2013 at 12:46 Comment(5)
if(d.Contains(a) && d.Contains(b))Inaudible
You should keep Console.ReadLine() outside the if loop.Intersexual
You're concatenating the strings b and a, so you're essentially writing if(d.Contains("someonedamage")) which won't work. Your if-statement fails and therefore will not hit Console.ReadLine(). Seriously, this is extremely basic debugging, please learn how to step through your code.Vaquero
This is really something you should be debugging yourself. You are getting a ton of answers showing you why this is incorrect, but simply putting in a couple of breakpoints and tracing through the code, looking at the values, will be much more beneficial to you as a programmer than all the answers flooding in here.Abate
@WonkotheSane: Agreed. I'm glad I didn't have SO (or the internet) when I was learning to program. If something didn't work, I had to figure it out myself. I couldn't just post the code and get a bunch of people telling me exactly how to fix it. It's an important skill to have.Ornithopter
D
43

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.

Dollfuss answered 16/4, 2013 at 12:48 Comment(2)
Hmm why if the number isnt at the 5th spot in every line?Jamestown
If it's not in the same spot, then that won't work. You will want to do a regular expression instead. \d* will get you all digits in a string, which will work for your example above.Dollfuss
G
10
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");
}
Gilded answered 16/4, 2013 at 12:57 Comment(0)
I
6

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

Indicatory answered 16/4, 2013 at 12:49 Comment(0)
L
3

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);  
Logistician answered 16/4, 2013 at 13:7 Comment(0)
A
2

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))
Alienism answered 16/4, 2013 at 12:51 Comment(0)
S
1

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

Sheer answered 16/4, 2013 at 12:48 Comment(0)
D
1

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

if (d.Contains(b) && d.Contains(a))
{  
    Console.WriteLine(" " + d);
    Console.ReadLine();
}
Diuresis answered 16/4, 2013 at 12:49 Comment(0)
S
1

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.

Steviestevy answered 16/4, 2013 at 12:50 Comment(0)
I
1
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();
Illuminance answered 16/4, 2013 at 12:50 Comment(0)
W
1

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);
Wherewith answered 16/4, 2013 at 12:51 Comment(0)
M
1

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;
}
Motoring answered 16/4, 2013 at 12:51 Comment(0)
R
1

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));
}
Rosabelle answered 16/4, 2013 at 12:52 Comment(1)
The Cast<string>() is unnecessary. You can also combine the Where() and Any(), since Any() can take a filter argument.Ornithopter
E
0

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();
Elevon answered 16/4, 2013 at 13:28 Comment(0)
D
0
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");
}
Do answered 3/9, 2014 at 9:20 Comment(0)
U
0

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.

Ungava answered 8/5, 2015 at 13:48 Comment(0)
T
0
 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));
          }
       }
Theo answered 25/11, 2016 at 21:17 Comment(0)
S
0
    public static bool In(this string str, params string[] p)
    {
        foreach (var s in p)
        {
            if (str.Contains(s)) return true;
        }
        return false;
    }
Scansorial answered 14/3, 2017 at 6:51 Comment(1)
One should generally add some words of explanation to one's answer.Bade

© 2022 - 2024 — McMap. All rights reserved.