Mastering in C# Substring | 2022

The Substring method in C# allows you to extract a portion of a string based on specific criteria. This powerful feature is handy when you need to manipulate or analyze only a part of a larger string.

In this comprehensive guide, we will explore the Substring method in detail, providing clear explanations and practical examples.

Extracting a Substring by Index

One common use case is to extract a substring starting from a specific index position.

string originalString = "Hello, World!";
string extractedSubstring = originalString.Substring(7);
// extractedSubstring will be "World!"

In this example, the Substring method starts from index 7 and retrieves the remaining portion of the string.

Extracting a Substring by Length

Example Usage 3: Extracting a Substring based on a Pattern The Substring method can also be used to extract substrings based on specific patterns or conditions. For example, extracting a substring based on the occurrence of a certain character:

string originalString = "OpenAI is amazing!";
int indexOfSpace = originalString.IndexOf(' ');
string extractedSubstring = originalString.Substring(0, indexOfSpace);
// extractedSubstring will be "OpenAI"

Here, the Substring method is combined with the IndexOf method to extract the substring before the first occurrence of a space character.

Extraction with Regular Expressions

For more complex substring extraction based on patterns, you can utilize regular expressions in conjunction with the Regex class in C#. Regular expressions provide a powerful way to define search patterns for extracting substrings.

using System.Text.RegularExpressions;
string originalString = "The product code is ABC-123-XYZ";
string pattern = @"[A-Z]{3}-\d{3}-[A-Z]{3}";
Match match = Regex.Match(originalString, pattern);
if (match.Success)
{
    string extractedSubstring = match.Value;
    // extractedSubstring will be "ABC-123-XYZ"
}

In this case, the regular expression pattern [A-Z]{3}-\d{3}-[A-Z]{3} is used to match a substring in the format of three uppercase letters, followed by a hyphen, three digits, another hyphen, and three uppercase letters. The Regex.Match method is used to find the first occurrence of this pattern in the original string.

Conclusion

The Substring method in C# is a powerful tool for manipulating strings and extracting substrings based on different criteria. In this article, we covered its usage for extracting substrings by index, length, and specific patterns.

By understanding the versatility of the Substring method and practicing with these examples, you’ll be well-equipped to handle string manipulation tasks effectively in C#.

Scroll to Top