首页 > 编程语言 > 详细

C++标准库里面没有字符分割函数split,自己编写函数实现字符串分割功能

时间:2019-09-06 22:23:44      阅读:118      评论:0      收藏:0      [点我收藏+]
#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
}

 

C++标准库里面没有字符分割函数split,自己编写函数实现字符串分割功能

原文:https://www.cnblogs.com/ming-4/p/11478144.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!