Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Strings and Text

Iterating over characters in a C# string

How to loop over a C# string: foreach and indexing over chars, surrogate pairs, EnumerateRunes, text elements, reverse loops, spans, and common pitfalls.

A C# string is a sequence of UTF-16 code units, each of type char. You can read them by index (s[i]), loop with foreach, or use LINQ, because string implements IEnumerable<char>. The Length property counts char values, not what a person would call "letters".

For plain English text this is the same thing. For emoji, many historic scripts, and letters built from a base plus accent marks, one visible symbol can take two or more char values. Then you need Rune (a full Unicode scalar value) or text elements (what users see as one character).

C#
foreach (char c in "abc")
{
    Console.WriteLine(c);
}

Try it

C# foreach, indexing and counting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# chars, runes and text elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public char this[int index] { get; }
public int Length { get; }
public CharEnumerator GetEnumerator()                  // used by foreach
public StringRuneEnumerator EnumerateRunes()
public ReadOnlySpan<char> AsSpan()

public static TextElementEnumerator StringInfo.GetTextElementEnumerator(string str)
public static bool char.IsSurrogatePair(string s, int index)
Member Description
s[i] The UTF-16 code unit at index i. Read-only: strings cannot be assigned through the indexer.
Length Number of char values.
EnumerateRunes() Yields Rune values (Unicode scalar values); a surrogate pair becomes one rune. Invalid lone surrogates become the replacement character U+FFFD.
StringInfo Counts and enumerates text elements (grapheme clusters).

Errors / undefined behavior: s[i] throws IndexOutOfRangeException when i is negative or not less than Length. Modifying a string while looping is not possible, because strings are immutable.

Usage notes

  • foreach is the clearest and the compiler turns it into an efficient indexed loop. Prefer it when you do not need the index.
  • Building a new string from chars: collect into a StringBuilder or char[] and construct once with new string(array). Do not use += in the loop.
  • Chars are not letters. char.IsLetter, char.IsDigit and similar methods have overloads taking (string, index), which look at the whole surrogate pair.
  • Reversing a string by reversing chars breaks surrogate pairs and combining marks. Reverse by text elements if the text is not plain ASCII.
  • Case and comparison belong to string methods, not char loops: see ToUpper() and StringComparison.
  • Performance. Looping over a ReadOnlySpan<char> (s.AsSpan()) avoids bounds checks in some patterns and lets you slice without allocating. See spans and memory.
  • Digits. char.IsDigit is true for digits of other scripts too; use c is >= '0' and <= '9' for ASCII digits only, and char.GetNumericValue for values.
  • Code points versus bytes. UTF-8 byte counts differ from Length; see Encoding.