Counting the number of characters inside double quotation marks

前端 未结 3 1996
失恋的感觉
失恋的感觉 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:35

    Here is a working version using recursion. For readability I split it in two functions that call each other recursively.

    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 
    
    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());
    }
    

提交回复
热议问题