-4

Can you please explain me how do i find in a simple way the number of times that a certain string occurs inside a big string? Example:

  string longString = "hello1 hello2 hello546 helloasdf";

The word "hello" is there four times. how can i get the number four. Thanks

EDIT: I would like to know how i find a two word string as well for example:

 string longString = "hello there hello2 hello4 helloas hello there";

I want to know the number of occurrences of "hello there".

EDIT 2: The regex method was the best for me (with the counts) but it does not find a word like this for example: ">word<" . Somehow, if I want to search for a word containing "<>" it skips it. Help?

Shakshuka
  • 19
  • 2
  • 8
  • 6
    http://xkcd.com/208/ – Aron Dec 17 '14 at 16:12
  • 1
    So you need to compare the "word" as well as "partial word", but what have you tried ? – Habib Dec 17 '14 at 16:13
  • http://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-within-a-string – Carl Dec 17 '14 at 16:16
  • I covered this for SQL here: the same method would be fine (and not require regex!): http://stackoverflow.com/questions/9789225/number-of-times-a-particular-character-appears-in-a-string/9789266#9789266 – Jon Egerton Dec 17 '14 at 16:17

4 Answers4

3

just use string.Split() and count the results:

string wordToFind = "hello";

string longString = "hello1 hello2 hello546 helloasdf";
int occurences = longString
                     .Split(new []{wordToFind}, StringSplitOptions.None)
                     .Count() - 1;

//occurences = 4

to answer your edit, just change wordToFind to hello there

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
1
string longString = "hello1 hello2 hello546 helloasdf";
var regex = new Regex("hello");

var matches = regex.Matches(longString);
Console.WriteLine(matches.Count);
Aron
  • 15,464
  • 3
  • 31
  • 64
  • Hi, this was the best method for me but when i want a word that contains ">word<" it doesn't find it when it exists. it skips <> please help. thx – Shakshuka Dec 21 '14 at 11:28
0

to do this with LINQ:

int count = 
    longString.Split(' ')
    .Count(str => str
    .Contains("hello", StringComparison.InvariantCultureIgnoreCase));

The only assumption here is that your longString is delimited by a space.

CuccoChaser
  • 1,059
  • 2
  • 15
  • 27
0

You can also use Linq to do this.

string longString = "hello1 hello2 hello546 helloasdf";
string target = "hello";
var count = longString.Split(' ').ToList<string>().Count(w => w.Contains(target));
Console.WriteLine(count);
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188