Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to find how many times a string(or substring) occurs in a large string c#

Tags:

string

c#

For school i had to make an assignment, which i handed in already, but the code i wrote is awful, i don't like what i ended up with. So, I'm curious, what would be considered the best possible way to solve the following question in C#:

'//4 How many times does “queen” occur in the Alice in Wonderland book? Write some code to count them.'

link to the book (pastebin): book

my code (pastebin): my code (ugly)

please when writing your answer, ignore my code. also, explain what your code does, and why you think it's the best possible solution. The amount of times the word "queen" occurs in the book should be 76.

like image 326
FrankK Avatar asked Feb 08 '23 12:02

FrankK


1 Answers

I won't post the full code, as I think it is useful for you to try this as an exercise, but I would personally go for a solution with the IndexOf overload that takes a starting position.

So something like (note: intentionally incorrect):

int startingPosition = 0;
int numberOfOccurrences = 0;
do {
  startingPosition = fullText.IndexOf("queen", startingPosition);
  numberOfOccurrences++;
} while( matchFound );
like image 158
CompuChip Avatar answered Feb 11 '23 03:02

CompuChip