C# Loop Over String CharsLoop over the characters in a string. Use a foreach-loop and a for-loop.
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
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.
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.
C# program that uses foreach on string
using System; class Program { static void Main() { 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.
C# program that uses reversed for-loop
using System; class Program { static void Main() { string id = "xy1"; // Loop over string in reverse. for (int i = id.Length - 1; i >= 0; i--) { Console.WriteLine("REVERSE: {0}", id[i]); } } }
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.
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.
Thus Loops are imperative and offer more control. Regular expressions offer more power in fewer characters.
A summary. 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.
© 2007-2021 sam allen.
see site info on the changelog.