C++ 字符串分割算法详解:stringstream 和 find/substr 方法
C++ 提供了多种方法来分割字符串,以下是两种常用的方法:
- 使用 stringstream 类
stringstream 类可以将字符串视为流进行处理,从而进行分割操作。具体步骤如下:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str = 'Hello World! This is a test string.';
stringstream ss(str); // 将字符串转换为 stringstream 对象
string token;
while (getline(ss, token, ' ')) // 以空格作为分隔符进行分割
{
cout << token << endl;
}
return 0;
}
输出结果:
Hello
World!
This
is
a
test
string.
- 使用 string 的 find 和 substr 方法
string 类提供了 find 和 substr 方法,可以通过查找分隔符的位置来截取子字符串,从而进行分割操作。具体步骤如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = 'Hello World! This is a test string.';
string delimiter = ' '; // 分隔符为空格
size_t pos = 0;
string token;
while ((pos = str.find(delimiter)) != string::npos) // 查找分隔符的位置
{
token = str.substr(0, pos); // 截取子字符串
cout << token << endl;
str.erase(0, pos + delimiter.length()); // 将已处理的部分从原字符串中删除
}
cout << str << endl; // 输出剩下的部分
return 0;
}
输出结果:
Hello
World!
This
is
a
test
string.
原文地址: https://www.cveoy.top/t/topic/nW0x 著作权归作者所有。请勿转载和采集!