Bruno Dias Bruno Dias - 1 year ago 89
C# Question

C# find words on a String

I'm trying to make a program that build a string of words and then find those words in the same string.

The first half of the question is working but I'm having problems with the second. The program finds the words, the first time and the last but, how do I found a eventual middle one? And then, how do I count them?

string strfinal;
string frase = "", texto = "";
string textoAEncontrar;
Console.WriteLine("Insira algum texto (carregue no * para terminar a escrita): ");

for (texto = ""; !texto.Equals("*");)
texto = Console.ReadLine();
if (texto.Length < 100)
frase = frase + " " + texto;

strfinal = frase.Substring(1, frase.Length - 2);


Console.WriteLine("O que deseja encontrar no texto escrito: ");
textoAEncontrar = Console.ReadLine();
int primeiraReferenciaNoTexto = strfinal.IndexOf(textoAEncontrar);
int ultimaReferenciaNoTexto = strfinal.LastIndexOf(textoAEncontrar);

if (strfinal.Contains(textoAEncontrar))

Console.WriteLine("A palavra {0} existe no index {1}", textoAEncontrar, primeiraReferenciaNoTexto);
Console.WriteLine("A palavra {0} existe no index {1}", textoAEncontrar, ultimaReferenciaNoTexto);
Console.WriteLine("A palavra {0} não existe", textoAEncontrar);


Answer Source

You need to chain your IndexOf calls, like so:

var i = -1
while (true)
     i = strFinal.IndexOf(textoAEncontrar, i+1);
     if (i == -1) break;
     Console.WriteLine("Found string at {0}", i);

You may need to improve the boundary checks above but this is the general idea.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download