的最後一個字符,我想檢查以下內容:c + +比較和替換字符串流
- 如果附加到
stringstream
的最後一個字符是一個逗號。 - 如果它是刪除它。
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" << ","
}
我懷疑這可能是更容易的在不添加最終逗號工作第一名。 – Galik
在某個地方有一個關於在由逗號分隔的循環中添加項目的問題,而不是在最後一項中添加逗號。編輯:可能[this](http://stackoverflow.com/questions/3496982/printing-lists-with-commas-c) – Tas
只是遍歷字符串的總數 - 1,在每個字符串之後添加一個逗號,以及之後循環添加最後一個字符串。如果沒有或一個字符串,則跳過循環。 –