Методы перебора строки в C++

Чтобы перебрать строку в C++, вы можете использовать несколько методов. Вот некоторые из наиболее часто используемых подходов:

  1. Использование цикла 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
    }
  2. Использование цикла For на основе диапазона (C++11 и более поздние версии):

    std::string str = "Hello, World!";
    for (char c : str) {
    // Access each character directly as 'c'
    // Perform operations or print the character
    }
  3. Использование итераторов:

    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
    }
  4. Использование стандартных алгоритмов (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
    });
  5. Использование цикла на основе индекса (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
    }

Эти методы позволяют перебирать каждый символ в строке и выполнять операции или печатать символы по мере необходимости.