在C++中,可以使用以下几种方法来从字符串中拆分字符:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string str = "Hello World";
std::vector<char> chars;
for (int i = 0; i < str.length(); i++) {
chars.push_back(str[i]);
}
// 输出拆分后的字符
for (char c : chars) {
std::cout << c << " ";
}
return 0;
}
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string str = "Hello World";
std::vector<std::string> substrings;
std::stringstream ss(str);
std::string substring;
while (getline(ss, substring, ' ')) {
substrings.push_back(substring);
}
// 输出拆分后的子字符串
for (std::string s : substrings) {
std::cout << s << " ";
}
return 0;
}
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string str = "Hello World";
std::vector<std::string> substrings;
size_t pos = 0;
std::string delimiter = " ";
while ((pos = str.find(delimiter)) != std::string::npos) {
std::string substring = str.substr(0, pos);
substrings.push_back(substring);
str.erase(0, pos + delimiter.length());
}
// 添加最后一个子字符串
substrings.push_back(str);
// 输出拆分后的子字符串
for (std::string s : substrings) {
std::cout << s << " ";
}
return 0;
}
这些方法可以根据具体的需求选择使用,它们都可以在C++中实现从字符串中拆分字符的功能。
领取专属 10元无门槛券
手把手带您无忧上云