如何在c++中去除向量中的空格

how to remove spaces in vector in c++

本文关键字:向量 空格 c++      更新时间:2023-10-16

下面是我为其编写的用于拆分字符串并存储在向量中的程序。如何从字符串中检索特定字段,并使用pipeline(|)符号再次连接期望的字符串。

   #include <iostream> 
   #include <vector>
   #include <string>
   #include <sstream>
   using namespace std;
    vector<string> split(string str, char delimiter)
    {
    vector<string> internal;
    stringstream ss(str); 
    string tok;
    while(getline(ss, tok, delimiter)) 
    {
       internal.push_back(tok);
     }
    return internal;
   }
  int main(int argc, char **argv) 
  {
    string myCSV = "Event#:11918124|1234|67893|USD||||444400090|||||302|45|USA|||||";
    vector<string> sep = split(myCSV, '|');
    for(int i = 0; i < sep.size(); ++i);
     cout << sep[0] << "|" << sep[3] << "|" << sep[7] << "|" << sep[14] << endl;
   }

输出:

Event#:11918124                                                           
1234                                                                         
67893                                                                        
USD                                                                                                                
444400090                                      
302                                                                                                                                                                                             
45                                                                                                                                       
USA

预期输出:

Event#:11918124|USD|444400090|USA

有人能帮我学习c++吗?我是c++的新手

您所需要做的就是连接记录中所需的字段。它们总是出现在相同的索引(0、3、7、14)处。所以在你的情况下,这很容易:

cout << sep[0] << "|" << sep[3] << "|" << sep[7] << "|" << sep[14] << endl;

顺便说一句,你对代码的"output:"是错误的。