How to count the times a string is repeated in another string in C #?

0

I have a string, for example: string cadena = "ABABBA"; and I want to know how many times the letter A is repeated next to the letter B , in the example I put in it I should result in 4 .

I had thought to use a for to traverse the string but that would only work with characters.

EDIT:

        string frase = "ABABBA";
        string palabra = "AB";
        string palabra2 = "BA";
        string nombre = "";
        int cont = 0;


        for (int i = 0; i < frase.Length; i++)
        {
            char caracter = frase[i];
            nombre = nombre + caracter;

            if (nombre.Contains(palabra) || nombre.Contains(palabra2))
            {
                cont++;
                nombre = "";
            }

        }
    
asked by Jason0495 02.03.2018 в 20:38
source

1 answer

4

You can try this:

using System.Text.RegularExpressions;

string cadena = "ABABBA";
int total = Regex.Matches(cadena, "AB").Count + Regex.Matches(cadena, "BA").Count;

I leave you a functional sandbox: link

    
answered by 02.03.2018 / 21:08
source