Data Structures and Algorithms • C# examples
String Algorithms and Character Sequences
Treat strings as sequences while accounting for immutability and character encoding.
Concept
Many string problems reduce to sequence operations: scanning, comparing, counting, or finding a pattern. In .NET, string is immutable, so repeated concatenation can allocate new strings. Unicode text may use multiple UTF-16 code units for one visible character; define whether an algorithm works on code units, runes, or grapheme clusters.
How to approach it
Clarify the text unit, normalize only when the task requires it, and use a mutable buffer or span for measured high-volume processing.
Complexity
A full scan is O(n); repeated substring copying can raise time and allocation costs.
C# example
string text = "algorithm";
int vowels = text.Count(character => "aeiou".Contains(character));
Console.WriteLine(vowels);
Expected result or behavior
The example counts five lowercase English vowels in “algorithm”.
Practice exercise
Change the example to handle uppercase vowels and state how accented characters should be treated.
Key takeaway: Text algorithms need an explicit definition of what counts as a character.