string 截取 c++
时间: 2024-05-25 14:07:13 浏览: 99
以下是两种C++中字符串截取的方法:
1. 使用C语言的strtok方法[^1]
```cpp
#include <iostream>
#include <vector>
#include <cstring>
std::vector<std::string> stringSplit(const std::string& strIn, char delim) {
char* str = const_cast<char*>(strIn.c_str());
std::string s;
s.append(1, delim);
std::vector<std::string> elems;
char* splitted = strtok(str, s.c_str());
while (splitted != NULL) {
elems.push_back(std::string(splitted));
splitted = strtok(NULL, s.c_str());
}
return elems;
}
int main() {
std::string str = "Hello,World,How,Are,You";
std::vector<std::string> result = stringSplit(str, ',');
for (const auto& s : result) {
std::cout << s << std::endl;
}
return 0;
}
```
输出:
```
Hello
World
How
Are
You
```
2. 使用stringstream和getline配合使用
```cpp
#include <iostream>
#include <vector>
#include <sstream>
std::vector<std::string> stringSplit(const std::string& str, char delim) {
std::stringstream ss(str);
std::string item;
std::vector<std::string> elems;
while (std::getline(ss, item, delim)) {
if (!item.empty()) {
elems.push_back(item);
}
}
return elems;
}
int main() {
std::string str = "Hello,World,How,Are,You";
std::vector<std::string> result = stringSplit(str, ',');
for (const auto& s : result) {
std::cout << s << std::endl;
}
return 0;
}
```
输出:
```
Hello
World
How
Are
You
```
阅读全文