Andrés Daza
Andrés Daza

Reputation: 3

check if there is a string followed by another c#

i need to verify if string is followed by other one in same string variable in C#. for example: string phrase= "life is is beautiful"; i need to set TRUE if there is a word followed by other separated by spaces or any. "is" is twice in this string variable. my code reads and find just one character folled by space and says 2. but it just read first character. i appreciate help.

  string frase, frase2;
        int secuencia;
       frase="life is is beautiful";            
        secuencia = 0;
        for (int i = 0; i < frase.Length; i++)
        {                                 
               if (frase[i]==' ' && frase[i+1]=='i')secuencia++;               
        }
        Console.WriteLine($"{secuencia} ");

Upvotes: 0

Views: 122

Answers (1)

Paddy
Paddy

Reputation: 33867

A lot depends on what size of strings you want to deal with and performance needs, but a naive way to approach this would be:

var splits = frase.split(" ");

for (int i = 0; i < splits.Length - 1; i++)
{                                 
     if (splits[i]==splits[i+1]) secuencia++;                
}

Upvotes: 1

Related Questions