How to count repeated words in a string and find your position?

Asked

Viewed 905 times

1

Imagine the alphabet, in this alphabet there are words from A-Z, but suddenly there are several letters A, like:

To-B-C-D-E-F-G-H-I-To-J-K-L-To-M-To-N-O-P-Q-To

The variable nomes below, is this alphabet. The variable procurar will only serve for me to choose which word repeated I want to see in the variable nomes.

In this model:

string procurar = "cachorro";
string nomes = "vaca cachorro vaca cachorro gato cavalo";
int index = ??
int total = ??

Anyone can help?

  • But count all the repeated words or just the word that is in the variable procurar ?

  • count the words that are in the variable nomes. The variable procurar serves to find the repeated name in the variable nomes.

1 answer

3


See if it helps you:

string procurar = "cachorro";
string nomes = "vaca cachorro vaca cachorro gato cavalo";
MatchCollection matches = Regex.Matches(nomes, procurar);
foreach (Match item in matches)
{
    Console.WriteLine(string.Format("{0} = {1}", procurar, item.Index));
}
Console.WriteLine(string.Format("achado {0} nomes ", matches.Count));

Functioning in the https://dotnetfiddle.net/dqjc8B

Browser other questions tagged

You are not signed in. Login or sign up in order to post.