c++ string 分割字符串
时间: 2024-02-05 21:09:06 浏览: 92
以下是两种C++中分割字符串的方法:
1. 使用stringstream和getline函数
```cpp
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> splitString(std::string str, char delimiter) {
std::vector<std::string> result;
std::stringstream ss(str);
std::string token;
while (getline(ss, token, delimiter)) {
result.push_back(token);
}
return result;
}
int main() {
std::string str = "This is a test";
std::vector<std::string> strList = splitString(str, ' ');
for (auto s : strList) {
std::cout << s << " ";
}
std::cout << std::endl;
return 0;
}
```
2. 使用find和substr方法
```cpp
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> splitString(std::string str, char delimiter) {
std::vector<std::string> result;
size_t start = 0;
size_t end = str.find(delimiter);
while (end != std::string::npos) {
result.push_back(str.substr(start, end - start));
start = end + 1;
end = str.find(delimiter, start);
}
result.push_back(str.substr(start, end));
return result;
}
int main() {
std::string str = "This-is-a-test";
std::vector<std::string> strList = splitString(str, '-');
for (auto s : strList) {
std::cout << s << " ";
}
std::cout << std::endl;
return 0;
}
```
阅读全文