c++ 字符串的分割

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了c++ 字符串的分割脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

c++ 字符串getline分割字符串存储进vector中

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

// I don't recommend using the std namespace in production code.
// For ease of reading here.
using namespace std;

// You could also take an existing vector as a parameter.
vector<string> split(string str, char delimiter) {
  vector<string> internal;
  stringstream ss(str); // Turn the string into a stream.
  string tok;
  
  while(getline(ss, tok, delimiter)) {
    internal.push_back(tok);
  }
  
  return internal;
}

int main(int argc, char **argv) {
  string myCSV = "one,two,three,four";
  vector<string> sep = split(myCSV, ',');

  // If using C++11 (which I recommend)
  /* for(string t : sep)
   *  cout << t << endl;
   */
   
  for(int i = 0; i < sep.size(); ++i)
    cout << sep[i] << endl;
}

和cin.getline()类似,但是cin.getline()属于istream流,而getline()属于string流,是不一样的两个函数这里使用的getline()属于string流。

脚本宝典总结

以上是脚本宝典为你收集整理的c++ 字符串的分割全部内容,希望文章能够帮你解决c++ 字符串的分割所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。