C++ Compare and replace last character of stringstream

前端 未结 1 1550
旧时难觅i
旧时难觅i 2020-12-20 03:56

I would like to check the following:

  1. If the last character appended to the stringstream is a comma.
  2. If it is remove it.
<
相关标签:
1条回答
  • 2020-12-20 04:41

    The way I often deal with these loops where you want to put something like a space or a comma between a list of items is like this:

    int main()
    {
        // initially the separator is empty
        auto sep = "";
    
        for(int i = 0; i < 5; ++i)
        {
            std::cout << sep << i;
            sep = ", "; // make the separator a comma after first item
        }
    }
    

    Output:

    0, 1, 2, 3, 4
    

    If you want to make it more speed efficient you can output the first item using an if() before entering the loop to output the rest of the items like this:

    int main()
    {
        int n;
    
        std::cin >> n;
    
        int i = 0;
    
        if(i < n) // check for no output
            std::cout << i;
    
        for(++i; i < n; ++i) // rest of the output (if any)
            std::cout << ", " << i; // separate these
    }
    

    In your situation the first solution could work like this:

        std::regex tok_pat("[^\\[\\\",\\]]+");
        std::sregex_token_iterator tok_it(command.begin(), command.end(), tok_pat);
        std::sregex_token_iterator tok_end;
        std::string baseStr = tok_end == ++tok_it ? "" : std::string(*tok_it);
    
        auto sep = ""; // empty separator for first item
    
        while (baseStr == "OVER")
        {
            // extract command parameters
            str << sep << "extracted_parameters";
            sep = ","; // make it a comma after first item
        }
    

    And the second (possibly more time efficient) solution:

        std::regex tok_pat("[^\\[\\\",\\]]+");
        std::sregex_token_iterator tok_it(command.begin(), command.end(), tok_pat);
        std::sregex_token_iterator tok_end;
        std::string baseStr = tok_end == ++tok_it ? "" : std::string(*tok_it);
    
        if (baseStr == "OVER")
        {
            // extract command parameters
            str << "extracted_parameters";
        }
    
        while (baseStr == "OVER")
        {
            // extract command parameters
            str << "," << "extracted_parameters"; // add a comma after first item
        }
    
    0 讨论(0)
提交回复
热议问题