Чтобы разделить строку в C++, можно использовать несколько методов. Вот некоторые распространенные подходы:
- Использование stringstream: вы можете использовать класс
std::stringstreamдля разделения строки на токены на основе разделителя. Вот пример:
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::string input = "Hello,World,How,Are,You";
std::vector<std::string> tokens;
std::stringstream ss(input);
std::string token;
while (std::getline(ss, token, ',')) {
tokens.push_back(token);
}
// Printing the tokens
for (const auto& t : tokens) {
std::cout << t << std::endl;
}
return 0;
}
- Использование функций find и substr. Вы можете использовать функции
std::string::findиstd::string::substrдля разделения строки. Вот пример:
#include <iostream>
#include <vector>
int main() {
std::string input = "Hello,World,How,Are,You";
std::vector<std::string> tokens;
size_t pos = 0;
std::string token;
while ((pos = input.find(',')) != std::string::npos) {
token = input.substr(0, pos);
tokens.push_back(token);
input.erase(0, pos + 1);
}
// Adding the last token
tokens.push_back(input);
// Printing the tokens
for (const auto& t : tokens) {
std::cout << t << std::endl;
}
return 0;
}
- Использование библиотеки Boost. Если у вас установлена библиотека Boost, вы можете использовать функцию
boost::splitдля разделения строки. Вот пример:
#include <iostream>
#include <vector>
#include <boost/algorithm/string.hpp>
int main() {
std::string input = "Hello,World,How,Are,You";
std::vector<std::string> tokens;
boost::split(tokens, input, boost::is_any_of(","));
// Printing the tokens
for (const auto& t : tokens) {
std::cout << t << std::endl;
}
return 0;
}
Это всего лишь несколько способов разделения строки в C++. Вы можете выбрать тот, который лучше всего соответствует вашим потребностям.