Чтобы перебрать строку в C++, вы можете использовать несколько методов. Вот некоторые из наиболее часто используемых подходов:
-
Использование цикла For:
std::string str = "Hello, World!"; for (size_t i = 0; i < str.length(); ++i) { // Access each character using str[i] // Perform operations or print the character } -
Использование цикла For на основе диапазона (C++11 и более поздние версии):
std::string str = "Hello, World!"; for (char c : str) { // Access each character directly as 'c' // Perform operations or print the character } -
Использование итераторов:
std::string str = "Hello, World!"; for (std::string::iterator it = str.begin(); it != str.end(); ++it) { // Access each character using *it // Perform operations or print the character } -
Использование стандартных алгоритмов (C++11 и выше):
std::string str = "Hello, World!"; std::for_each(str.begin(), str.end(), [](char c) { // Access each character directly as 'c' // Perform operations or print the character }); -
Использование цикла на основе индекса (C++17 и более поздние версии):
std::string str = "Hello, World!"; for (auto&& [index, character] : str | std::views::enumerate) { // Access each character using character // Perform operations or print the character }
Эти методы позволяют перебирать каждый символ в строке и выполнять операции или печатать символы по мере необходимости.