ways to check if a string start with another string in c#?
- User
ways to check if a string start with another string in c#?
- Assistant
There are several ways to check if a string starts with another string in C#. Here are some examples:
- Using the StartsWith() method:
string str1 = "hello world"; string str2 = "hello";
if(str1.StartsWith(str2)) { Console.WriteLine("The string starts with the given prefix."); }
- Using the Substring() method:
string str1 = "hello world"; string str2 = "hello";
if(str1.Substring(0, str2.Length) == str2) { Console.WriteLine("The string starts with the given prefix."); }
- Using the IndexOf() method:
string str1 = "hello world"; string str2 = "hello";
if(str1.IndexOf(str2) == 0) { Console.WriteLine("The string starts with the given prefix."); }
Note that these methods are case-sensitive. If you want to perform a case-insensitive check, you can use the StringComparison.OrdinalIgnoreCase option in the StartsWith() and IndexOf() methods.