1. 程式人生 > >c++拆分string型字串存到vector中

c++拆分string型字串存到vector中

//對資料進行拆分放到vec中
void split_string(const std::string str,
          std::vector<std::string>&vec,
          const std::string cut) {
  std::string::size_type begin_index, end_index;
  end_index = str.find(cut);
  begin_index = 0;
  while(std::string::npos != end_index)
  {
    vec.push_back(str.substr(begin_index, end_index-begin_index));
    begin_index = end_index+ cut.size();
    end_index = str.find(cut, begin_index);
  }
  if(begin_index != str.length())
    vec.push_back(str.substr(begin_index));

}

函式使用:

split_string(first_line_str, first_line_vec,",");