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
Release: 2024-11-30 10:37:08
Original
979 people have browsed it

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'
}
Copy after login

Iterator-Based For Loop

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

Traditional For Loop

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

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'
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template