21xrx.com
2025-03-25 13:42:56 Tuesday
文章检索 我的文章 写文章
C++ 字符串类分割方法
2023-06-22 16:26:49 深夜i     17     0
C++ 字符串类 分割方法 字符串分割 字符串切割

C++作为一门常用的编程语言,其字符串类在各种应用场景中极为重要,其中字符串分割是其常见操作之一。本文将介绍C++字符串分割的几种方法。

1. istringstream类方法

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string str, char sep=' '){
  vector<string> vec;
  istringstream ss(str);
  string token;
  while (getline(ss, token, sep)) {
    vec.push_back(token);
  }
  return vec;
}
int main() {
  string str = "hello world, I am a student.";
  vector<string> vec = split(str);
  for (auto i : vec)
    cout << i << endl;
  
  return 0;
}

该方法使用istringstream类分割字符串,依据给定的分割符,默认为' ',将字符串分成多个子串,并存在一个字符串向量中。其优点为:使用简单方便,适用于小字符串的分割。

2. boost库方法

#include <iostream>
#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
vector<string> split(string str, char sep=' '){
  tokenizer<char_separator<char>> tok(str, char_separator<char>(sep));
  vector<string> vec(tok.begin(), tok.end());
  return vec;
}
int main() {
  string str = "hello world, I am a student.";
  vector<string> vec = split(str);
  for (auto i : vec)
    cout << i << endl;
  
  return 0;
}

该方法采用了boost库中的tokenizer类,其使用同样也比较简单。该方法可以处理更大的字符串分割,并且可以根据多个分割符进行分割。

3. strtok函数方法

#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
vector<string> split(char* str, char* sep=" "){
  vector<string> vec;
  char* token = strtok(str, sep);
  while (token) {
    vec.push_back(token);
    token = strtok(NULL, sep);
  }
  return vec;
}
int main() {
  char str[] = "hello world, I am a student.";
  vector<string> vec = split(str);
  for (auto i : vec)
    cout << i << endl;
  
  return 0;
}

该方法是使用标准库中的strtok函数进行字符串分割的方法,其使用麻烦,但是速度比较快。需要注意的是,该函数最好仅在C++中使用,因为其在多线程环境下并不是线程安全的。

综上所述,字符串分割在C++编程中非常常见,但方法多种多样。应该根据自己的需求合理选择方法,以达到最佳效果。

  
  

评论区

    相似文章