Search code examples
c#stringchar

How can I count how often a specific char appears before other specific char appears for the first time?


I have a string like asdafahxlkax.

How can I count that a appears 3 times before the first x appears?


Solution

  • String str = "asdafahxlkax"; 
    char[] chars = str.ToCharArray();
    
    int counter = 0;
    for (int i = 0; i < chars.Length; i++)
    {
        if(chars[i] == 'a')
        {
            counter++;
        }
        else if(chars[i] == 'x')
        {
            if(counter == 3)
            {
                // success
            }
            else
            {
                // fail
            }
        }
    }
    

    You need to define if you want this to fail when x is contained 0 times. But in general this is a simple approach.