Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 182 ยท Strings

Working with Strings

A practical guide to C# string methods - Substring, IndexOf, Contains, Replace, Split, Join, Trim, Pad, Insert, Remove, case conversion, spans and counting characters.

The string type ships with dozens of methods, and a handful of them cover almost every real task: finding text, cutting pieces out, replacing, splitting a line into fields, cleaning whitespace and changing case. This lesson walks through them in the order you will need them, explains the pitfalls (there are several) and finishes with a faster slicing technique using spans.

Remember the central rule from Strings: strings are immutable, so every method here returns a new string (or a number or a bool) and never changes the original.

Searching: Contains, IndexOf, StartsWith, EndsWith

Contains, StartsWith and EndsWith answer yes/no questions. IndexOf returns the zero-based position of the first match, or -1 when there is none. LastIndexOf searches from the end, and IndexOfAny looks for any of several characters.

C# Finding things in a string

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.

Two habits will save you trouble. First, always check for -1 before you use the result as an index. Second, pass a StringComparison when you search with a string argument: the overloads without it use culture-sensitive rules for IndexOf, StartsWith and EndsWith, but the char overloads are always ordinal.

Cutting: Substring and slicing

Substring(start) returns everything from start to the end; Substring(start, length) returns length characters. Both throw ArgumentOutOfRangeException when the numbers do not fit. Ranges give the same result with friendlier syntax: text[start..end] where end is exclusive.

C# Substring versus ranges

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.

For real file names use Path.GetFileName and friends instead of cutting by hand (see Files and Paths). The manual version is a good way to practice the index arithmetic, which is the same in every language: the length of a slice is end - start.

Replacing, inserting and removing

Replace swaps every occurrence of a character or substring for another. Insert(index, text) puts text at a position, and Remove(index) or Remove(index, count) deletes part of the string.

C# Replace, Insert and Remove

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.

Replace replaces all matches, not only the first one. If you need only the first, combine IndexOf with Remove and Insert, or use a regular expression (see Regular Expressions). Replacing with an empty string is a neat way to delete a substring everywhere.

Splitting and joining

Split cuts a string at separators and returns an array; string.Join is its inverse. Split takes options that turn out to be very useful: StringSplitOptions.RemoveEmptyEntries drops empty pieces and StringSplitOptions.TrimEntries trims whitespace from each piece (.NET 5+).

C# Split and Join

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.

A real CSV file has quoted fields with commas inside them, which Split cannot handle. Use it for simple, controlled formats only. The count argument (Split('=', 2)) is handy for key=value lines whose value may itself contain the separator.

Trimming and padding

Trim() removes whitespace from both ends, TrimStart() and TrimEnd() from one end. Pass characters to trim those instead. PadLeft and PadRight extend a string to a minimum width, which is the classic way to line up columns.

C# Trim and Pad

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.

Interpolation can align too ({name,-15}), see Interpolation and Formatting; Pad is useful when the width is computed or when you build the text in pieces.

Case conversion

ToUpper and ToLower use the current culture. In a Turkish locale "title".ToUpper() gives "TฤฐTLE" with a dotted capital ฤฐ, which breaks code that compares against "TITLE". Use ToUpperInvariant and ToLowerInvariant for identifiers and protocol text, and ToUpper() only for text shown to people. For comparisons, skip case conversion and use StringComparison.OrdinalIgnoreCase, which does not allocate.

C# Case conversion done right

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.

Counting characters

Counting how often each character occurs is a common exercise, and it combines indexing, char methods and a dictionary. Because dictionary ordering is not something to rely on, we sort before printing.

C# Character frequencies

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.

The char helpers IsLetter, IsDigit, IsUpper and IsWhiteSpace are Unicode-aware, so they work for letters outside ASCII too. A subtlety for later: a char is a UTF-16 code unit, so some visible characters (emoji, for instance) occupy two of them. Unicode, Rune and Encoding explains how to count what users actually see.

Span-based slicing: avoiding allocations

Every Substring call allocates a new string. When you only need to look at part of a string, a ReadOnlySpan<char> gives you a view into the original characters with no copying. AsSpan(start, length) or a range on a span creates one, and spans have most of the search methods you know: IndexOf, StartsWith, Trim, Contains and SequenceEqual, plus int.Parse overloads that accept spans.

C# Parsing with spans

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.

This whole parse allocates no intermediate strings. Spans are an advanced topic with their own rules (they live on the stack, so they cannot be stored in fields of ordinary classes or used across await); see Spans and Memory. For ordinary application code, Substring and Split are perfectly fine; reach for spans in hot paths that process large volumes of text. The Split on spans returning ranges needs .NET 9 or later.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "hello".IndexOf('z') return?

    IndexOf returns -1 when nothing matches. Always test for -1 before using the result as an index.
  2. 2. What is the value of "a,b,,c".Split(',', StringSplitOptions.RemoveEmptyEntries).Length?

    The pieces are a, b, an empty entry and c. RemoveEmptyEntries drops the empty one, leaving three.
  3. 3. Which call is the best way to test whether a file name ends with .CSV regardless of case?

    EndsWith with OrdinalIgnoreCase ignores case, uses file-name appropriate ordinal rules and does not allocate a lowered copy.
  4. 4. What does "7".PadLeft(3, '0') produce?

    PadLeft adds characters on the left until the string has the requested width.
  5. 5. Why use ReadOnlySpan<char> instead of Substring in a hot parsing loop?

    A span is a window onto existing memory. Substring copies the characters into a new string each time.

Summary

  • Search with Contains, IndexOf (returns -1 for no match), StartsWith and EndsWith; pass a StringComparison for string arguments.
  • Cut with Substring or ranges, and change text with Replace, Insert and Remove; all return new strings.
  • Split with RemoveEmptyEntries | TrimEntries handles simple delimited data; string.Join reverses it.
  • Trim, PadLeft and PadRight clean and align text; use invariant case conversion for non-human text.
  • ReadOnlySpan<char> slices without allocating, which is valuable in performance-critical parsing.

Next: Interpolation and Formatting