Count number of commas within a string except for commas between double quotes

counter, java, performance, string

Solution

This implementation has two differences:

- Use `CharSequence` instead of String

- No need of a `boolean` value to track if we are inside a quoted subsequence.

The function:

public static int countCharOfString(char quote, CharSequence sequence) {

    int total = 0, length = sequence.length();

    for(int i = 0; i < length; i++){
        char c = sequence.charAt(i);
        if (c == '"') {
            // Skip quoted sequence
            for (i++; i < length && sequence.charAt(i)!='"'; i++) {}
        } else if (c == quote) {
            total++;
        }
    }

    return total;
 }

Problem

I have the following function to count the number of commas (or any other character) in a String without counting those inside double quotes. I want to know if there's a better way to achieve this or even if you can find some case where this function can crash. ``` public int countCharOfString(char c, String s) { int numberOfC = 0; boolean doubleQuotesFound = false; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == c && !doubleQuotesFound){ numberOfC++; }else if(s.charAt(i) == c && doubleQuotesFound){ continue; }else if(s.charAt(i) == '\"'){ doubleQuotesFound = !doubleQuotesFound; } } return numberOfC; } ``` Thanks for any advise

Original source