C ++比较并替换stringstream的最后一个字符

its*_*ani 2 c++ regex stringstream

我想检查以下内容:

  1. 如果追加到的最后一个字符stringstream是逗号。
  2. 如果是,将其删除。

std::stringstream str;
str << "["
//loop which adds several strings separated by commas

str.seekp(-1, str.cur); // this is to remove the last comma before closing bracket

str<< "]";
Run Code Online (Sandbox Code Playgroud)

问题是如果循环中未添加任何内容,则会从字符串中删除左括号。因此,我需要一种方法来检查最后一个字符是否为逗号。我这样做是这样的:

if (str.str().substr(str.str().length() - 1) == ",")
{
    str.seekp(-1, rteStr.cur);
}
Run Code Online (Sandbox Code Playgroud)

但是我对此并不很好。有一个更好的方法吗?

关于循环:

循环用于标记通过套接字接收的一组命令,并将其格式化以通过另一个套接字发送给另一个程序。每个命令以一个OVER标志结尾。

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);
while (baseStr == "OVER")
{
    //extract command parameters
    str << "extracted_parameters" << ","
}
Run Code Online (Sandbox Code Playgroud)

Gal*_*lik 5

我经常在想要在项目列表之间放置空格或逗号之类的循环的方式是这样的:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

0, 1, 2, 3, 4
Run Code Online (Sandbox Code Playgroud)

如果要提高速度效率,可以if()在进入循环之前使用来输出第一个项目,以输出其余项目,如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,第一个解决方案可以像这样工作:

    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
    }
Run Code Online (Sandbox Code Playgroud)

第二种(可能更节省时间)解决方案:

    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
    }
Run Code Online (Sandbox Code Playgroud)