C# String StartsWith() Method

https‮gi.www//:‬iftidea.com

The StartsWith() method in C# is used to determine whether a string starts with a specified substring. It returns a Boolean value of true if the string starts with the specified substring, and false otherwise.

The syntax of the StartsWith() method is as follows:

string.StartsWith(substring);

Here, substring is the substring to check for at the beginning of the string.

For example, to check if a string starts with the substring "Hello", you can use the following code:

string text = "Hello World";
bool startsWithHello = text.StartsWith("Hello");
Console.WriteLine(startsWithHello);  // Output: true

In this example, the StartsWith() method is used to check if the string "Hello World" starts with the substring "Hello". Since it does, the startsWithHello variable is assigned a value of true, which is then printed to the console using the WriteLine() method.

You can also use the StartsWith() method to perform case-insensitive checks by using the StringComparison enumeration. For example, to check if a string starts with the substring "hello" in a case-insensitive manner, you can use the following code:

string text = "Hello World";
bool startsWithHello = text.StartsWith("hello", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(startsWithHello);  // Output: true

In this example, the StartsWith() method is used to check if the string "Hello World" starts with the substring "hello" in a case-insensitive manner. The StringComparison.OrdinalIgnoreCase parameter is used to specify case-insensitive comparison. Since the string starts with "Hello", which is equivalent to "hello" in a case-insensitive comparison, the startsWithHello variable is assigned a value of true, which is then printed to the console using the WriteLine() method.