Чтобы токенизировать строку в C++, вы можете использовать различные методы. Вот некоторые часто используемые подходы:
-
Использование строкового потока:
#include <iostream> #include <sstream> #include <vector> int main() { std::string input = "Hello, how are you?"; std::stringstream ss(input); std::string token; std::vector<std::string> tokens; while (getline(ss, token, ' ')) { tokens.push_back(token); } // Print the tokens for (const auto& t : tokens) { std::cout << t << std::endl; } return 0; } -
Использование strtok:
#include <iostream> #include <cstring> #include <vector> int main() { std::string input = "Hello, how are you?"; char* cstr = new char[input.length() + 1]; std::strcpy(cstr, input.c_str()); char* token = std::strtok(cstr, " "); std::vector<std::string> tokens; while (token != nullptr) { tokens.push_back(token); token = std::strtok(nullptr, " "); } // Print the tokens for (const auto& t : tokens) { std::cout << t << std::endl; } delete[] cstr; return 0; } -
Использование регулярных выражений (регулярных выражений):
#include <iostream> #include <regex> #include <vector> int main() { std::string input = "Hello, how are you?"; std::regex re("\\s+"); std::vector<std::string> tokens(std::sregex_token_iterator(input.begin(), input.end(), re, -1), std::sregex_token_iterator()); // Print the tokens for (const auto& t : tokens) { std::cout << t << std::endl; } return 0; }
Это всего лишь несколько примеров того, как можно токенизировать строку в C++. Каждый метод имеет свои преимущества и может оказаться более подходящим в зависимости от конкретных требований вашей программы.