这是一个使用递归的工作版本。为了便于阅读,我将其拆分为两个递归调用的函数。
我使用指向最后一个引号后的字符的指针来跟踪如果标记的数量不匹配要打印什么,同时将其初始化为nullptr,因此它也可以跟踪如果我们遇到任何引号。
#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());
}