Check if a string starts with a given prefix in C#
This article illustrates the different techniques to check if a string starts with a given prefix in C#.
1. Using String.StartsWith() method
The standard solution to determine if a string starts with a given prefix or not is using the String.StartsWith() method. It returns true if the specified string matches the beginning of the string instance; false otherwise.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string website = "google.com"; string prefix = "google"; bool result = website.StartsWith(prefix); Console.WriteLine(result); // True } } |
2. Using Enumerable.Any() method
To match a string that starts with any of the given list of prefixes, you can use LINQ’s Enumerable.Any() method. It returns true if any element of the sequence satisfies the specified condition. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; public class Example { public static void Main() { string[] companies = { "google", "microsoft", "youtube" }; string website = "google.com"; bool result = companies.Any(prefix => website.StartsWith(prefix)); Console.WriteLine(result); // True } } |
3. Using Regex.IsMatch() method
Another option is to use regular expressions to match a string that starts with any of the given list of prefixes. This can be done using the Regex.IsMatch() method, which returns true if the string matches the given regular expression.
The following code example demonstrates how to use the Regex.IsMatch() method for determining whether a string starts with any of the given strings. Here, ^ matches with the start of the string, and (google|microsoft|youtube) matches the string from the beginning with any of the values separated by |.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string website = "google.com"; bool result = Regex.IsMatch(website, "^(google|microsoft|youtube)"); Console.WriteLine(result); // True } } |
That’s all about checking if a string starts with a given prefix in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)