Counting the number of characters inside double quotation marks

前端 未结 3 1991
失恋的感觉
失恋的感觉 2021-01-28 01:23

I want to find the number of characters inside a double quotation mark.

For example :

Case 1

\"Hello World\" , \"Some

output :

3条回答
  •  情歌与酒
    2021-01-28 01:41

    Please help me to figure out what approach shall I use to solve the above-given problem.

    Instead of using recursion, you may use this simpler approach that runs in linear time:

    void countCharsWithinDoubleQuotes(const std::string& input)
    {
        size_t ans = 0;
        bool quoteStarted = false;
    
        // Iterate through the string and get the required counts
        for (const auto& ch : input)
        {
            // Toggle the quote switch
            if (ch == '"')
                quoteStarted = !quoteStarted;
    
            // Keep counting the characters after a starting double quote
            else if (quoteStarted)
                ++ans;
        }
    
        // If a closing quote was not found, it was not balanced
        if (quoteStarted) // quoteDidNotEnd
        {
            std::cout << "Error";
        }
    
        // Print the number of characters within all the double quotes
        else
        {
            std::cout << ans;
        }
    }
    

    Edit:

    If you need a better explanation, it is in JohnFilleau's comment below the question.

提交回复
热议问题