C# String Functions
string is a sequence of UTF-16 characters. It is a reference type that behaves like a value: == compares the text, and a string can never be changed after it is created — every method that seems to modify one, like ToUpper or Replace, returns a new string. This lesson covers how to write string literals, compare and search text correctly, take strings apart and join them, and build large strings efficiently with StringBuilder.
The examples are complete dotnet new console programs (.NET 8 or later).
String Basics
Three Facts About Strings
Three facts explain most string behaviour in C#:
- Immutable.
s.ToUpper();on its own line does nothing useful: the result is thrown away. Writes = s.ToUpper();. Immutability makes strings safe to share between threads and to use as dictionary keys. - Compared by value.
a == bis true when both contain the same characters, even if they are different objects. - Can be
null.""(orstring.Empty) is an empty string;nullis no string at all, and calling a method on it throws.string.IsNullOrEmptyandstring.IsNullOrWhiteSpacecheck both at once.
A single character has its own type, char, written in single quotes: 'A'. Indexing a string, s[0], returns a char.
String Literals
C# has four kinds of string literal, and choosing the right one removes most escaping headaches:
| Literal | Syntax | Use for |
|---|---|---|
| regular | "Tab:\tQuote:\"" | short text; escapes like \n, \t, \", \\, \u00E9 |
| verbatim | @"C:\data\file.txt" | Windows paths and regular expressions: backslashes are literal; write "" for one quote |
| interpolated | $"Hi {name}" | embedding values; combine with @ as $@"..." |
| raw (C# 11) | """....""" | JSON, XML, SQL and other text that contains quotes; no escapes at all |
Raw and Interpolated Strings
A raw string literal starts and ends with at least three double quotes. In the multi-line form, the column of the closing """ sets the left margin: that much indentation is removed from every line, so the literal can be indented with your code. For an interpolated raw string, the number of $ signs says how many braces open an expression — with $$, a single { is ordinary text, which is exactly what JSON needs.
// Four literal styles: verbatim, escaped, raw, and interpolated raw.
string path = @"C:\data\file.txt";
string escaped = "Tab:\tQuote:\" Newline follows\n(end)";
string name = "Ada";
int year = 1843;
string raw = """
{
"name": "Ada",
"note": "no \escapes here"
}
""";
string json = $$"""{"name": "{{name}}", "year": {{year}}}""";
Console.WriteLine(path);
Console.WriteLine(escaped);
Console.WriteLine(raw);
Console.WriteLine(json);
Console.WriteLine($"{name,-6}|{year,6}|{Math.PI:F3}");
Output:
C:\data\file.txt
Tab: Quote:" Newline follows
(end)
{
"name": "Ada",
"note": "no \escapes here"
}
{"name": "Ada", "year": 1843}
Ada | 1843|3.142
Alignment (,-6) and format specifiers (:F3) work in every interpolated string; the full list is in Input & Output.
Comparing Strings
Ordinal vs Culture-Aware
== compares strings ordinally: character code by character code, case-sensitive. That is right for identifiers, file names, keys and protocol text. For anything else, say what you mean with a StringComparison value:
Ordinal/OrdinalIgnoreCase— fast, exact, culture-independent. The default choice for program data.CurrentCulture/CurrentCultureIgnoreCase— follows the user's language rules. Use it to sort or compare text that a person will read.InvariantCulture— culture-aware but fixed; rarely the best choice.
Beware that some methods are culture-sensitive by default (string.Compare, StartsWith(string), ToUpper()) while others are ordinal (==, Equals, Contains, Replace). Passing a StringComparison explicitly removes the guesswork, and code analyzers can enforce it.
// Ordinal vs culture-aware comparison, and null-safe checks.
string a = "file.TXT", b = "FILE.txt";
Console.WriteLine(a == b); // False
Console.WriteLine(string.Equals(a, b, StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine(a.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)); // True
// Ordinal: 'a' (97) comes after 'B' (66). Culture: alphabetical, apple before Banana.
Console.WriteLine(string.Compare("apple", "Banana", StringComparison.Ordinal) < 0); // False
Console.WriteLine(string.Compare("apple", "Banana", StringComparison.CurrentCulture) < 0); // True
string? missing = null;
Console.WriteLine(string.IsNullOrEmpty(missing)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // True
Console.WriteLine(missing == ""); // False: null is not empty
Output:
False
True
True
False
True
True
True
False
Searching and Modifying
Search
Contains, StartsWith and EndsWith answer yes-or-no questions. IndexOf and LastIndexOf return the position of the first or last match, or -1 when there is none — always check for -1 before using the result as an index. For patterns rather than fixed text (an e-mail address, a date), use System.Text.RegularExpressions.Regex.
Extract and Modify
Substring(start, length) and the range syntax s[start..end] extract part of a string. Trim, TrimStart and TrimEnd remove whitespace or chosen characters; PadLeft and PadRight add them; Replace, Insert and Remove do what their names say. Use ToUpperInvariant/ToLowerInvariant to normalise program data, because the culture-aware ToUpper gives surprising results in some languages (in Turkish, "i".ToUpper() is "İ").
// Searching returns positions; every "modifying" call returns a new string.
string text = "The quick brown fox jumps over the lazy dog";
Console.WriteLine(text.Length);
Console.WriteLine(text.IndexOf("fox"));
Console.WriteLine(text.LastIndexOf("the"));
Console.WriteLine(text.IndexOf("cat"));
Console.WriteLine(text.Contains("QUICK", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(text[4..9]); // characters 4 to 8
Console.WriteLine(text.Substring(40)); // from 40 to the end
Console.WriteLine(text.Replace("lazy", "sleepy").ToUpperInvariant());
Console.WriteLine(" padded ".Trim() + "|");
Console.WriteLine("42".PadLeft(5, '0'));
Console.WriteLine(new string('-', 10));
Console.WriteLine(string.Concat(Enumerable.Repeat("ab", 3)));
Output:
43
16
31
-1
True
quick
dog
THE QUICK BROWN FOX JUMPS OVER THE SLEEPY DOG
padded|
00042
----------
ababab
Split & Join
Split and Join
Split cuts a string at every separator and returns an array of the pieces; string.Join glues an array or list back together with a separator. Two StringSplitOptions flags clean up real-world input: RemoveEmptyEntries drops empty pieces (from doubled or trailing separators) and TrimEntries removes the spaces around each piece. Passing no separator splits on any whitespace.
// Splitting messy input and joining it back together.
string csv = "Ada, 36, London,,";
string[] pieces = csv.Split(',');
Console.WriteLine(pieces.Length); // includes the two empty pieces
string[] clean = csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Console.WriteLine(string.Join("|", clean));
string[] words = "one two\tthree\nfour".Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(words.Length);
Console.WriteLine(string.Join(", ", words.Select(w => w.ToUpperInvariant())));
Output:
5
Ada|36|London
4
ONE, TWO, THREE, FOUR
Split is fine for simple, well-behaved data. Real CSV files have quoted fields that contain commas ("Lovelace, Ada"), so for CSV use a library such as CsvHelper instead of writing your own parser.
StringBuilder
Because strings are immutable, s += "x" copies the whole of s into a new string every time. In a loop that adds 10,000 pieces, that is 10,000 ever-larger copies, and the work grows with the square of the length. System.Text.StringBuilder keeps a growable buffer instead: Append, AppendLine, AppendJoin and Insert edit the buffer in place, and ToString() produces the final string once. For a handful of concatenations, or a single interpolated string, plain strings are just as fast and easier to read — reach for StringBuilder when you build text in a loop.
// Build a multiplication table in one buffer, then convert it to a string once.
using System.Text;
var sb = new StringBuilder();
for (int row = 1; row <= 3; row++)
{
sb.AppendJoin(' ', Enumerable.Range(1, 4).Select(col => (row * col).ToString().PadLeft(2)));
sb.Append('\n');
}
sb.Insert(0, "Table:\n");
Console.Write(sb.ToString());
Console.WriteLine($"{sb.Length} chars");
Output:
Table:
1 2 3 4
2 4 6 8
3 6 9 12
43 chars
Characters and Unicode
Length counts UTF-16 code units, not the characters a person sees. Most text uses one code unit per character, but emoji and many rare scripts need two (a surrogate pair), and an accented letter can be stored as a letter plus a combining mark. When you count, truncate or reverse user-visible text, work with text elements through System.Globalization.StringInfo, or with Rune values via EnumerateRunes().
// Length counts UTF-16 code units; StringInfo counts what the reader sees.
using System.Globalization;
string word = "café";
string thumbsUp = "\U0001F44D"; // one emoji, two UTF-16 code units
Console.WriteLine(word.Length);
Console.WriteLine(thumbsUp.Length);
Console.WriteLine(new StringInfo(thumbsUp).LengthInTextElements);
Console.WriteLine(thumbsUp.EnumerateRunes().Count());
Output:
4
2
1
1
Practice
Exercises
- Write
IsPalindrome(string s)that ignores case, spaces and punctuation, so that"A man, a plan, a canal: Panama"returnstrue. Usechar.IsLetterOrDigit. - Count the words in a paragraph and print the five most frequent, case-insensitively, using
Splitand a dictionary withStringComparer.OrdinalIgnoreCase. - Turn
"user_first_name"into"UserFirstName"withSplit,char.ToUpperInvariantandstring.Concat. - Build a 1,000-line report once with
+=and once withStringBuilder, time both withSystem.Diagnostics.Stopwatch, and compare.
The demo 16_strings.cs collects more string operations.