C#C#

C#: Strings – code examples

Contents

Count words

Strings#groupby#split#text#tuple
Use case: Text analysis, e.g. the most frequent words in a document.
string text = "this is a test this is good";
var haeufig = text.Split(' ')
    .GroupBy(w => w)
    .Select(g => (Wort: g.Key, Anzahl: g.Count()))
    .OrderByDescending(x => x.Anzahl);

foreach (var (wort, anzahl) in haeufig.Take(2))
    Console.WriteLine($"{wort}: {anzahl}");   // this: 2, is: 2

GroupBy forms groups per word, OrderByDescending sorts stably by frequency; named tuples make the result readable.

Regular expression

Strings#regex#pattern#matches
Use case: Find email addresses, phone numbers or patterns in text.
using System.Text.RegularExpressions;

string text = "Contact: ada@example.com, bob@test.org";
foreach (Match m in Regex.Matches(text, @"[\w.]+@[\w.]+\.\w+"))
    Console.WriteLine(m.Value);

Console.WriteLine(Regex.Replace("Phone 12345", @"\d+", "#"));   // Phone #

Verbatim strings (@"...") save doubled backslashes. Matches returns all matches, Replace replaces patterns.

Manipulate strings

Strings#string#stringbuilder#split#join
Use case: Clean up input, split and assemble text.
string s = "  C# is fun  ";
Console.WriteLine(s.Trim().ToLower());                       // c# macht spaß
Console.WriteLine(string.Join("-", "x,y,z".Split(',')));      // x-y-z
Console.WriteLine("Python".Replace("y", "Y") + " " + "abc".StartsWith("a")); // PYthon True

var sb = new System.Text.StringBuilder();
for (int i = 1; i <= 3; i++) sb.Append(i).Append(';');
Console.WriteLine(sb);                                       // 1;2;3;

Strings are immutable – every method returns a new string. For many append operations in loops, StringBuilder is more efficient.