Substring
Learn to take part of a string with Substring.
Substring for a slice
In C#, you take a part of a string with the Substring method. The single-argument form Substring(int startIndex) returns everything from the given position to the end. Positions are zero-based, so the first character sits at index 0.
For example, "Hello".Substring(3) returns "lo" because the third index points at l. The original string is unchanged; the result is a brand new string that you usually assign to a variable.
The length parameter
The two-argument form Substring(int startIndex, int length) takes a fixed number of characters starting at the given position. It is handy when you need to pull a fixed-width code out of a longer string.
For example, "20240115".Substring(0, 4) returns "2024"; it grabs the first four characters. If start plus length exceeds the string length, ArgumentOutOfRangeException is thrown, so a bounds check is needed.
The original string is unchanged
Strings in C# are immutable, so a Substring call never mutates the original; it returns a new string. To use the result you should assign it to a variable.
For example, when you write string part = name.Substring(2);, name stays the same and part holds the new string. The same rule applies to other string methods such as Split, Replace and Trim.
Exercise Extract the domain
The atIndex variable already holds the position of '@' in email. Use Substring with atIndex + 1 to grab the rest of the string into a variable called domain. Then print domain with Console.WriteLine.
Show example solution
atIndex is already computed for you. Call email.Substring(atIndex + 1), store it in domain, then print it with Console.WriteLine.
Example solution:
using System;
class Program
{
static void Main()
{
string email = "alex@codeblanks.com";
int atIndex = email.IndexOf('@');
string domain = email.Substring(atIndex + 1);
Console.WriteLine(domain);
}
}
Test yourself
-
What does "Hello".Substring(3) return?
Console.WriteLine("Hello".Substring(3));- Hel
- lo
- llo
- Hello
Show answer
lo — Correct! Index 3 is 'l' and the slice to the end is 'lo'.
-
Take the first four characters
string code = "2024AB78"; string year = code____; Console.WriteLine(year);Show answer
string code = "2024AB78"; string year = code.Substring(0, 4); Console.WriteLine(year); -
What happens when the index is out of bounds?
string s = "abc"; string part = s.Substring(5);- Returns an empty string
- Throws FormatException
- Throws ArgumentOutOfRangeException
- Returns null
Show answer
Throws ArgumentOutOfRangeException — Correct! ArgumentOutOfRangeException fires when start exceeds the length.