I want to find the number of characters inside a double quotation mark.
For example :
Case 1
\"Hello World\" , \"Some
output :
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.