iterating string in cpp
To iterate over a string in C++, you can use a range-based for loop or a traditional for loop. Here's an example using both methods:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// Using a range-based for loop
for (char c : str) {
std::cout << c << " ";
}
std::cout << std::endl;
// Using a traditional for loop
for (int i = 0; i < str.length(); i++) {
std::cout << str[i] << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
First, we include the necessary header files,
<iostream>
and<string>
, which provide the necessary functions and classes for input/output and string manipulation, respectively.We define the
main
function, which is the entry point of the program.Inside the
main
function, we declare a string variablestr
and assign it the value "Hello, World!".We use a range-based for loop to iterate over each character
c
in the stringstr
. The loop will automatically iterate over each character in the string, from the first to the last.Inside the loop, we print each character followed by a space using the
std::cout
object, which is part of theiostream
library. This will output each character of the string separated by spaces.After the range-based for loop, we print a newline character (
std::endl
) to move to the next line in the output.Next, we use a traditional for loop to iterate over each character in the string
str
. The loop uses an integer variablei
to represent the index of each character in the string.The loop condition is
i < str.length()
, which ensures that the loop continues untili
reaches the length of the string. This is because the indices of a string start from 0 and go up tolength - 1
.Inside the loop, we print each character of the string by accessing it using the index
i
(str[i]
).After the traditional for loop, we print a newline character (
std::endl
) to move to the next line in the output.Finally, we return 0 to indicate successful execution of the program.
This program will output:
H e l l o , W o r l d !
H e l l o , W o r l d !
The first line is the output of the range-based for loop, which prints each character of the string separated by spaces. The second line is the output of the traditional for loop, which also prints each character of the string separated by spaces.