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.

Download  Run Code

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:

Download  Run Code

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 |.

Download  Run Code

That’s all about checking if a string starts with a given prefix in C#.