Substring in C#
A substring is a contiguous sequence of characters within a string. In other words, a substring in C# is a portion of a string. The string class in C# represents a string. Here is a list of commonly asked questions related to C# substring with code examples.
- How to get a substring from a string?
- How to get a substring of the first n characters from a string?
- How to get a substring after a character?
- How to get a substring before a character?
- How to get a substring with a start and end index?
- How to get a substring from index to end?
- How to get a substring between two strings?
- How do I get the last 4 characters of a string in C#?
1. String.Substring method to get a substring of a string in C#
In C#, a string is represented by the String class. The String.Substring method retrieves a substring from a string instance in C#. The method has the following two overloaded forms.
- Substring(Int32) - Retrieves a substring from the specified position to the end of the string.
- Substring(Int32, Int32 - Retrieves a substring from this instance from the specified position for the specified length.
Here's an example of using the Substring method in C#:
string str = "Hello World";
string substr1 = str.Substring(0, 5); // substr1 will contain "Hello"
string substr2 = str.Substring(6); // substr2 will contain "World"
In this example, we declare a string variable str containing the "Hello World" value. We then use the Substring method to extract two substrings from the original string.
The first substring is extracted using the overload of Substring that takes two arguments. The first argument is the starting index of the substring (in this case, 0), and the second argument is the length of the substring (in this case, 5). This means that the substr1 variable will contain the first 5 characters of the str string, which is "Hello".
The second substring is extracted using the overload of Substring that takes only one argument. In this case, we pass in the starting index of the substring (which is 6). This means that the substr2 variable will contain the remaining characters of the str string after the first space character, which is "World".
2. Get the first n characters substring from a string in C#
String characters are zero-indexed. This means the position of the first characters in a string starts at the 0th position.
Let’s say you want to get a substring of the first 12 characters from a string. We can use the Substring method and pass it starting index 0 and length of the substring 12 to get the first 12 char substring from a string.
The following code snippet is an example of retrieving a 12 chars substring from a string.
// A long string
string bio = "Mahesh Chand is a founder of C# Corner. Mahesh is also an author, speaker, and software architect. Mahesh founded C# Corner in 2000.";
// Get first 12 characters substring from a string
string authorName = bio.Substring(0, 12);
Console.WriteLine(authorName);
Now, if you want to retrieve a substring, everything after the 12th position, you can simply pass the starting position in the string to get the rest of the string as a substring. For example, the following code snippet gets a substring that has all characters after the 12th position in a string.
// Get everything else after 12th position
string authorBio = bio.Substring(12);
Console.WriteLine(authorBio);
The complete code example is listed in Listing 1.
using System;
class Program
{
static void Main(string[] args)
{
// A long string
string bio = "Mahesh Chand is a founder of C# Corner. Mahesh is also an author, " +
"speaker, and software architect. Mahesh founded C# Corner in 2000.";
// Get first 12 characters substring from a string
string authorName = bio.Substring(0, 12);
Console.WriteLine(authorName);
// Get everything else after 12th position
string authorBio = bio.Substring(12);
Console.WriteLine(authorBio);
Console.ReadKey();
}
}
Listing 1.
The output of Listing 1 looks like Figure 1.
Figure 1.
3. Get a substring with a start and end index
The Substring method's first parameter is the substring's starting index. The second parameter is the number of characters, including whitespaces. Finally, you can use the String. Length to find out the end index of a string.
The following code snippet gets a substring from index eight until the string's end.
// Get a string between a start index and end index
string str = "How to find a substring in a string";
int startIndex = 7;
int endIndex = str.Length - 7;
string title = str.Substring(startIndex, endIndex);
Console.WriteLine(title);
You can also pass the second argument of Substring to get several characters. For example, the following code snippet gets a substring of 15 characters starting at index 8.
// Get next 15 characters from starting index
string title15 = str.Substring(startIndex, 15);
The output looks like Figure 2.
Figure 2.
4. Get a substring after or before a character in C#
You can use the Substring method to find a substring before the first occurrence of a specified character. You can pass the starting index as 0 and length as the position of the specified characters.
The following code snippet retrieves a substring before a comma's first occurrence.
// Get a substring after or before a character
string authors = "Mahesh Chand, Henry He, Chris Love, Raj Beniwal, Praveen Kumar";
string stringBeforeChar = authors.Substring(0, authors.IndexOf(","));
Console.WriteLine(stringBeforeChar);
The following code snippet retrieves a substring after a comma's first occurrence.
// Get a substring after a character
string stringAfterChar = authors.Substring(authors.IndexOf(",") + 2);
Console.WriteLine(stringAfterChar);
5. Find the occurrence of substrings in a string in C#
You can find the position of a substring in a string by using String.IndexOf method. The following code snippet returns the position of a substring in a string.
int firstStringPosition = authors.IndexOf("Henry");
6. Get a substring between two strings in C#
You can use the Substring method to find a substring between two strings. First, you need to find the position of the two strings in the string. Then use the first string position as the starting position and find the string's length by subtracting the first string's position from the second string's position.
The following code snippet retrieves a substring between ‘Henry’ and ‘Beniwal’.
// Get a substring after or before a character
string authors = "Mahesh Chand, Henry He, Chris Love, Raj Beniwal, Praveen Kumar";
// Get a substring between two strings
int firstStringPosition = authors.IndexOf("Henry");
int secondStringPosition = authors.IndexOf("Beniwal");
string stringBetweenTwoStrings = authors.Substring(firstStringPosition,
secondStringPosition - firstStringPosition + 7);
Console.WriteLine(stringBetweenTwoStrings);
The substring includes both strings as well. If you want to exclude the two strings, ‘Henry’ and ‘Beniwal’, from the substring, you can increase the starting position and reduce the length parameters in the Substring method.
7. Split a string into substrings separated by a character in C#
We can use String. Split method to separate a string into an array of strings. You can also further search for a character in a string and retrieve a substring from it.
The following code snippet splits a string into an array of substrings that are separated by a comma. After that, the Substring method is further used to retrieve substrings followed by ‘:’ from the substring.
// Extract value of each attribute
string author = "Name: Mahesh Chand, Book: C# Programming, Publisher: C# Corner, Year: 2020";
string[] authorInfo = author.Split(", ");
foreach (string info in authorInfo)
{
Console.WriteLine(" {0}", info.Substring(info.IndexOf(": ") + 1));
}
How do I get the last 4 characters of a string in C#?
This code snippet returns the last 4 characters of a string in C#. You can replace 5 with any number n to get the last n numbers of a string in C#.
string author = "Mahesh Chand is founder of C# Corner";
string substr = author[^4..];
Summary
This article and code sample taught us about substrings in C# and how to use String.Substring method to retrieve various types of substrings.
To learn more about C# strings, check out the String In C# tutorial to learn more about strings and how to work with strings in C#.