计算双引号内的字符数 [英] Counting the number of characters inside double quotation marks
问题描述
我想找到双引号内的字符数.
I want to find the number of characters inside a double quotation mark.
例如:
案例1
"Hello World",一些
"Hello World" , "Some
output:错误//在Some后面缺少引号
output : Error // missing quotation marks after Some
案例2
"Hello Word","Some"
"Hello Word" , "Some"
输出:14//所有引号均已完整
output : 14 // All quotation marks are complete
我已经编写了使用递归来计算字符总数,第一个引号的索引和引号总数的程序.
I have written the program for counting the total characters, the index of the first quotation mark and the total number of quotations marks using recursion.
我应该使用什么方法来解决这个问题?
What approach shall I use to solve this problem?
推荐答案
此处是使用递归的有效版本.为了提高可读性,我将其分为两个递归调用的函数.
Here is a working version using recursion. For readability I split it in two functions that call each other recursively.
我正在使用指向最后一个引号后的字符的指针来跟踪标记数不匹配时要打印的内容,同时将其初始化为 nullptr
这样也可以跟踪我们是否遇到了引号.
I'm using a pointer to the character after the last quotation mark to keep track of what to print if the number of marks don't match, and at the same time initializing it to nullptr
so it also keeps track of if we have encountered any quotation marks at all.
#include <iostream>
int count_marks(const char* str, int count = 0, const char* err = nullptr);
int count_between_marks(const char* str, int count = 0, const char* err = nullptr);
int count_marks(const char* str, int count, const char* err) {
if (!*str) {
if (!err) {
std::cout << "Error // No quotation marks at all\n";
return -1;
}
std::cout << count << " // All quotation marks are complete\n";
return count;
}
if (*str == '\"')
return count_between_marks(str+1, count, str+1);
else
return count_marks(str+1, count, err);
}
int count_between_marks(const char* str, int count, const char* err) {
if (!*str) {
std::cout << "Error // No quotation marks after " << err << '\n';
return -1;
}
if (*str == '\"')
return count_marks(str+1, count, err);
else
return count_between_marks(str+1, count+1, err);
}
int main() {
std::string s("\"Hello World\", \"Some\"");
std::string s2("\"Hello World\", \"Some");
std::string s3("Hello World, Some");
count_marks(s.c_str());
count_marks(s2.c_str());
count_marks(s3.c_str());
}
这篇关于计算双引号内的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!