Iterate through characters of a string in C#
This post will discuss how to iterate through the characters of a string in C#.
1. Using foreach loop
The foreach loop provides a simple, elegant way to iterate through the characters of a string. The following example demonstrates how to use foreach to print every character of a string in the console.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string str = "Hello"; foreach (char c in str){ Console.WriteLine(c); } } } |
Output:
H
e
l
l
o
2. Using for loop
We can also iterate over characters of a string using the regular for loop and use the loop counter index to access each character. This is demonstrated below. Note that this is typically faster than the foreach statement.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string str = "Hello"; for (int i = 0; i < str.Length; i++) { char c = str[i]; Console.WriteLine(c); } } } |
Output:
H
e
l
l
o
That’s all about iterating through characters of a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)