-5

I'm trying to get a word from a bunch of randomtyped characters or words, for example, I want check if the word dog exists in the following string:

string animal = "MyNewdogIsVeryPlayful";

How would I manage this?

Kjartan
  • 18,591
  • 15
  • 71
  • 96
Steven Borges
  • 401
  • 1
  • 3
  • 16

2 Answers2

9

How about:

string animal = "MyNewdogIsVeryPlayful";
bool containsDog = animal.ToUpperInvariant().Contains("DOG");

This will work regardless of the casing of the original string.

If the string is camel-cased, and you want to split the string up to get the constituent words, have a look at this answer here.

Community
  • 1
  • 1
Baldrick
  • 11,712
  • 2
  • 31
  • 35
3
string animal = "MyNewdogIsVeryPlayful";
bool isDogContained = animal.Contains("dog");

Assuming you want to check for different animals, you could create an extension method (place it in a separate static class):

public static bool Contains(this string listOfAnimals, string animalToSearchFor){
    return listOfAnimals.Contains(animalToSearchFor);
}

That will let you do e.g.:

bool doesItContainLion = "MyNewdogIsVeryPlayful".Contains("lion");
Kjartan
  • 18,591
  • 15
  • 71
  • 96
  • I know. But then, that was what he wanted! :) (See my comment below the OP). – Kjartan Nov 12 '13 at 14:02
  • I think the OP said in his comments that this is exactly what he wants. – Baldrick Nov 12 '13 at 14:02
  • Yes it's what I wanted, thanks Kjartan, at first it didn't work for me, but then I realized I used the wrong variable in my code, so I thought .Contains didn't actualy work! – Steven Borges Nov 12 '13 at 14:15