Loop Over String CharsLoop over the characters in a string. Use a foreach-loop and a for-loop.
This page was last reviewed on Nov 28, 2023.
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.
Shows a loopShows a reverse loop
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.
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.
Shows a loop
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.Shows a reverse loop
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]); }
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 28, 2023 (edit).
© 2007-2024 Sam Allen.