2016-03-08 114 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