Home
C#
Loop Over String Chars
Updated Nov 28, 2023
Dot Net Perls
Loop, string chars. A loop iterates over individual string characters. It allows processing for each char. In C# different types of loops (even reversed loops) can be used.
Loop types. The foreach-loop and the for-loop are available for this purpose. Inside the body of a for-loop, we can access chars with the string indexer.
String Chars
Loop, String Array
First example. We look at 2 loops where we iterate over each char in a string. The string you loop over can be a string literal, a variable, or a constant.
Version 1 We use the foreach-loop to iterate over the chars. We print each character to the console.
foreach
Version 2 This loop has more complex syntax, but from the perspective of the machine, it is not more complex—it does the same thing.
for
using System; const string value = "abc"; // Version 1: use foreach-loop. foreach (char c in value) { Console.WriteLine(c); } // Version 2: use for-loop. for (int i = 0; i < value.Length; i++) { Console.WriteLine(value[i]); }
a b c a b c
Reversed for-loop. The for-loop is in most ways more powerful than the foreach-loop. We can use any index we want to access the string—here we decrement from the last to the first.
using System; string id = "xy1"; // Loop over string in reverse. for (int i = id.Length - 1; i >= 0; i--) { Console.WriteLine("REVERSE: {0}", id[i]); }
REVERSE: 1 REVERSE: y REVERSE: x
Performance notes. It is sometimes easier for the JIT compiler to optimize the loops if you do not hoist the Length check outside of the for-loop.
Tip It is not often helpful to store the length in a local variable. With any change, testing is essential.
String Length
StringBuilder. For long inputs where we build up an output, a StringBuilder is important. It means we do not have to worry about thousands of appends happening in edge cases.
StringBuilder
Regex. Sometimes using a loop is far more efficient than a Regex. Another advantage of loops is the ability to test each character and alert the user to special characters.
Regex.Match
Thus Loops are imperative and offer more control. Regular expressions offer more power in fewer characters.
Often we use loops to test for special patterns in strings. The performance here is good because it only needs to make one pass over the string.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 28, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen