How to count text between two quotes?

So simple: all I want is:

Input : Hey, "I didn't see you there" "Once again"

Output : 2

Inpu t: Hey, "I didn't see you there" "Once again" "Just kidding"

Output : 3

Count spaces never worked with me because: there are spaces between quotes in the text

The code I have tested but never worked because of the reason above ...

static int CountWords(string text)
{
    int wordCount = 0, index = 0;

    while (index < text.Length)
    {

        while (index < text.Length && !char.IsWhiteSpace(text[index]))
            index++;

        wordCount++;

        while (index < text.Length && char.IsWhiteSpace(text[index]))
            index++;
    }
    return wordCount;
}

      

+3


source to share


2 answers


Regular expressions will work wonderfully here:

var count = Regex.Matches(input, "\".*?\"").Count;

      



Alternatively, the other suggestions for counting the number of quotes and dividing by two would work as well:

var count = input.Count(c => c == '"') / 2;

      

+4


source


You can count quotes and divide by 2.



int counter = 0;
int answer = 0;

foreach (char c in input)
{
    if(c == "\"")
    {
        counter++;
    }
}

answer = counter / 2;

      

0


source







All Articles