温馨提示×

c++字符串分割的方法是什么

c++
小亿
82
2024-01-04 17:53:34
栏目: 编程语言

在C++中,有多种方法可以将字符串分割为子字符串。下面是一些常见的方法:

  1. 使用字符串流(stringstream):可以使用字符串流将字符串按照指定的分隔符分割成子字符串。首先,包含 <sstream> 头文件,然后使用 std::getline 函数和 std::stringstream 类来实现。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main() {
  std::string str = "Hello,World,Example,String";
  std::stringstream ss(str);
  std::vector<std::string> tokens;
  std::string token;

  while (std::getline(ss, token, ',')) {
    tokens.push_back(token);
  }

  for (const auto& elem : tokens) {
    std::cout << elem << std::endl;
  }

  return 0;
}
  1. 使用字符串的成员函数:C++的字符串类(std::string)提供了一些成员函数来处理字符串,包括 findsubstr。可以使用这些函数来遍历字符串并找到分隔符,然后提取子字符串。
#include <iostream>
#include <string>
#include <vector>

int main() {
  std::string str = "Hello,World,Example,String";
  std::vector<std::string> tokens;
  std::string delimiter = ",";
  size_t pos = 0;

  while ((pos = str.find(delimiter)) != std::string::npos) {
    std::string token = str.substr(0, pos);
    tokens.push_back(token);
    str.erase(0, pos + delimiter.length());
  }

  tokens.push_back(str);

  for (const auto& elem : tokens) {
    std::cout << elem << std::endl;
  }

  return 0;
}

这些方法可以根据具体情况选择使用,根据分隔符的不同,可以调整代码中的分隔符参数。

0