在C++中,使用std::string
和std::istringstream
可以更安全、更方便地分割字符串
#include<iostream>
#include <sstream>
#include<vector>
#include<string>
int main() {
std::string input = "This is a sample string";
std::istringstream iss(input);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, ' ')) {
tokens.push_back(token);
}
for (const auto& t : tokens) {
std::cout << t << std::endl;
}
return 0;
}
在這個示例中,我們首先創建了一個std::istringstream
對象iss
,并將輸入字符串傳遞給它。然后,我們使用std::getline
函數從iss
中讀取以空格分隔的子字符串,并將它們存儲在std::vector<std::string>
容器中。最后,我們遍歷并打印分割后的字符串。
注意:std::getline
默認情況下使用換行符作為分隔符,但是在這個例子中,我們將空格作為分隔符傳遞給它。