Home >Backend Development >C++ >How Can I Iterate Through Characters in a C String?

How Can I Iterate Through Characters in a C String?

Linda Hamilton
Linda HamiltonOriginal
2024-11-30 10:37:08982browse

How Can I Iterate Through Characters in a C   String?

Looping Through Characters in a String in C

Iterating over the characters of a string is a common task in programming. Here are the different methods to achieve this in C :

Range-Based For Loop (C 11 onwards)

std::string str = ???;
for (char& c : str) {
    // Perform actions on the character 'c'
}

Iterator-Based For Loop

std::string str = ???;
for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
    // Perform actions on the character '*it'
}

Traditional For Loop

std::string str = ???;
for (std::string::size_type i = 0; i < str.size(); ++i) {
    // Perform actions on the character 'str[i]'
}

Null-Terminated Character Array Loop

For C-style null-terminated strings, use:

char* str = ???;
for (char* it = str; *it; ++it) {
    // Perform actions on the character '*it'
}

The above is the detailed content of How Can I Iterate Through Characters in a C String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn