C++常見問題: 字符串分割函數 split


C++標准庫里面沒有字符分割函數split ,這可太不方便了,我已經遇到>3次如何對字符串快速分割這個問題了。列幾個常用方法以備不時之需。

 

方法一: 利用STL自己實現split 函數(常用,簡單,直觀)

原型: vector<string> split(const string &s, const string &seperator);

輸入一個字符串,一個分隔符字符串(可包含多個分隔符),返回一個字符串向量。這是我最喜歡的方法,因為它最直觀,在平常也最常用。實現及測試代碼如下

 

#include <vector>
#include <string>
#include <iostream>
using namespace std;

vector<string> split(const string &s, const string &seperator){
  vector<string> result;
  typedef string::size_type string_size;
  string_size i = 0;
  
  while(i != s.size()){
    //找到字符串中首個不等於分隔符的字母;
    int flag = 0;
    while(i != s.size() && flag == 0){
      flag = 1;
      for(string_size x = 0; x < seperator.size(); ++x)
      if(s[i] == seperator[x]){
        ++i;
        flag = 0;
        break;
      }
    }
    
    //找到又一個分隔符,將兩個分隔符之間的字符串取出;
    flag = 0;
    string_size j = i;
    while(j != s.size() && flag == 0){
      for(string_size x = 0; x < seperator.size(); ++x)
      if(s[j] == seperator[x]){
        flag = 1;
        break;
      }
      if(flag == 0) 
      ++j;
    }
    if(i != j){
      result.push_back(s.substr(i, j-i));
      i = j;
    }
  }
  return result;
}

int main(){
  string s = "a,b*c*d,e";
  vector<string> v = split(s, ",*"); //可按多個字符來分隔;
  for(vector<string>::size_type i = 0; i != v.size(); ++i)
    cout << v[i] << " ";
  cout << endl;
  //輸出: a b c d
}

 

 

 

@egmkang 提供了一段更簡潔高效的代碼,實現如下:

void SplitString(const std::string& s, std::vector<std::string>& v, const std::string& c)
{
  std::string::size_type pos1, pos2;
  pos2 = s.find(c);
  pos1 = 0;
  while(std::string::npos != pos2)
  {
    v.push_back(s.substr(pos1, pos2-pos1));
 
    pos1 = pos2 + c.size();
    pos2 = s.find(c, pos1);
  }
  if(pos1 != s.length())
    v.push_back(s.substr(pos1));
}

 

方法二: 用C語言中的strtok 函數來進行分割

原型:  char *strtok(char *str, const char *delim);

strtok函數包含在頭文件<string.h>中,對於字符數組可以采用這種方法處理。當然也可以將字符數組轉換成字符串之后再使用法一。測試代碼如下

#include <string.h>
#include <stdio.h>

int main(){
  char s[] = "a,b*c,d";
  const char *sep = ",*"; //可按多個字符來分割
  char *p;
  p = strtok(s, sep);
  while(p){
    printf("%s ", p);
    p = strtok(NULL, sep);
  }
  printf("\n");
  return 0;
}
//輸出: a b c d

 

方法三: boost庫中包含了split 函數

boost庫有很多方法來實現split,也包含了一個split函數,可以直接使用,非常實用而且強大但是得自己下載boost庫。使用代碼如下

#include <boost/algorithm/string.hpp>
#include <iostream>
#include <string>
#include <vector>

using namespace std;
using namespace boost;

void print( vector <string> & v )
{
  for (size_t n = 0; n < v.size(); n++)
    cout << "\"" << v[ n ] << "\"\n";
  cout << endl;
}

int main()
{
  string s = "a,b, c ,,e,f,";
  vector <string> fields;

  cout << "Original = \"" << s << "\"\n\n";

  cout << "Split on \',\' only\n";
  split( fields, s, is_any_of( "," ) );
  print( fields );

  cout << "Split on \" ,\"\n";
  split( fields, s, is_any_of( " ," ) );
  print( fields );

  cout << "Split on \" ,\" and elide delimiters\n"; 
  split( fields, s, is_any_of( " ," ), token_compress_on );
  print( fields );

  return 0;
}

輸出結果如下:

Original = "a,b, c ,,e,f,"

Split on ',' only
"a"
"b"
" c "
""
"e"
"f"
""

Split on " ,"
"a"
"b"
""
"c"
""
""
"e"
"f"
""

Split on " ," and elide delimiters
"a"
"b"
"c"
"e"
"f"
""

 

在C++中還有很多方法來實現split 函數,cplusplus.com有個C++ split 專題,詳細比較分析了幾種實現方法(見下圖)。鏈接見文末參考文獻。 

#---------------------------------------------------------------------------------#

參考文獻

《Accelerated C++》 by Andrew Koenig, Barbara E. Moo.

"Split a string" from cplusplus.com

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM