2016-03-08 83 views
1

的最后一个字符,我想检查以下内容:c + +比较和替换字符串流

  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<< "]"; 

的问题是,如果没有在所述环路中加入,开口支架从字符串中移除。所以我需要一种方法来检查最后一个字符是否是逗号。我这样做是这样的:

if (str.str().substr(str.str().length() - 1) == ",") 
{ 
    str.seekp(-1, rteStr.cur); 
} 

但我对此感觉不太好。有一个更好的方法吗?

关于循环:

回路用于标记化的一组通过插座接收到的命令的并格式化通过另一插口发送到其他程序。每个命令以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" << "," 
} 
+0

我怀疑这可能是更容易的在不添加最终逗号工作第一名。 – Galik

+0

在某个地方有一个关于在由逗号分隔的循环中添加项目的问题,而不是在最后一项中添加逗号。编辑:可能[this](http://stackoverflow.com/questions/3496982/printing-lists-with-commas-c) – Tas

+1

只是遍历字符串的总数 - 1,在每个字符串之后添加一个逗号,以及之后循环添加最后一个字符串。如果没有或一个字符串,则跳过循环。 –

回答

2

我经常处理这些循环要放像项目清单之间的空格或逗号的方法是这样的:

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 
    } 
} 

输出:

0, 1, 2, 3, 4 

如果您想提高速度,可以使用输出第一个项目之前进入循环输出项目的其余部分是这样的:

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 
} 

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

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 
    } 

而第二个(可能更多的时间高效的)解决方案:

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

问题是,我的字符串来自sregex_token_iterator,我使用while循环来检测令牌结束。没有办法知道有多少琴弦会在那里。 – itsyahani

+0

@itsyahani我明白了。那么,如果插入逗号首先可以避免,那么提取逗号似乎还有很多工作要做。你可以在这个问题上发布更多关于循环的知识,所以也许有人可以提出一个更适合我的解决方案? – Galik

+0

我编辑了我的问题。谢谢 – itsyahani