
A loop iterates over individual string characters. It allows processing for each char. The foreach-loop and the for-loop are available for this purpose. The string indexer returns a char value.
First, let's look at two 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. The first loop uses foreach, and the second uses for.
This C# program loops over the characters in a string. It uses a foreach and for loop.
Program that uses foreach on string [C#]
using System;
class Program
{
static void Main()
{
const string s = "peace";
foreach (char c in s)
{
Console.WriteLine(c);
}
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine(s[i]);
}
}
}
Output
p
e
a
c
e
p
e
a
c
e
Performance tip. Note that for performance, 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.
Here we note that for long inputs where you build up an output, using StringBuilder is important. It means we don't have to worry about hundreds or thousands of appends happening in edge cases.
StringBuilder Secrets StringBuilder Performance
Let's discuss regular expressions and how they compare to loops. 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. However, regular expressions offer more power in fewer characters.
Regex Versus Loop Regex Type
We saw a simple method to loop over each character in your string. The performance here is good because it only needs to make one pass over the string. Often, you need to use loops over strings instead of Regex because there are special patterns you need to test for. You can find a benchmark of different ways to loop over strings with the for-loop in the C# language on this site as well.
String For-Loop Loop Constructs