string
charsA loop iterates over individual string
characters. It allows processing for each char
. In C# different types of loops (even reversed loops) can be used.
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.
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.
foreach
-loop to iterate over the chars. We print each character to the console.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
for
-loopThe 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
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.
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.
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
.