C# String StartsWith

Summary: in this tutorial, you will learn how to use the C# String StartsWith to determine if the beginning of a string matches a specified string.

Introduction to the C# String StartsWith method

The String StartsWith() method allows you to check if the beginning of a string matches the specified string, taking into account the culture during comparison.

Here’s the syntax of the StartsWith() method:

public bool StartsWith (string value);Code language: C# (cs)

The StartsWith method accepts a parameter value that represents the string to match. It returns true if the string value matches the beginning of the current string or false otherwise.

For example, the following program uses the StartsWith() method to check if the beginning of the string "To live or not to live" starts with the substring "To live":

using static System.Console;

var message = "To live or not to live";
var result = message.StartsWith("To live");
WriteLine(result);Code language: C# (cs)

Output:

TrueCode language: C# (cs)

The StartsWith() method returns true as expected.

The following example uses the StartsWith() method to check if the string "To live or not to live" starts with the string "To Live" with the letters T and L in uppercase:

using static System.Console;

var message = "To live or not to live";
var result = message.StartsWith("To Live");
WriteLine(result);Code language: C# (cs)

Output:

FalseCode language: C# (cs)

In this example, the StartsWith() method returns false because it compares strings case-sensitively. To specify the string comparison’s rules, you can use the following overload of the StartsWith() method:

public bool StartsWith (
   string value, 
   StringComparison comparisonType
);Code language: C# (cs)

In this overload, you can specify the comparisonType with one of the StringComparison enum value that determines how the StartsWith compare the strings.

For example, the following program illustrates how to use the StartsWith method to match the string case-insensitively using the StringComparison.OrdinalIgnoreCase option:

using static System.Console;

var message = "To live or not to live";

var result = message.StartsWith(
    "To Live", 
    StringComparison.OrdinalIgnoreCase
);

WriteLine(result);Code language: C# (cs)

Output:

TrueCode language: C# (cs)

The StartsWith() method has another overload that accepts three parameters:

public bool StartsWith (
   string value, 
   bool ignoreCase, 
   System.Globalization.CultureInfo? culture
);Code language: C# (cs)

In this syntax:

  • ignoreCase is set to true to ignore the case during the comparison; otherwise false.
  • culture represents the cultural information used to compare the strings. If the culture is null, the method uses the current culture.

Summary

  • Use the C# String StartsWith() method to determine whether the beginning of a string matches a specified string.
Was this tutorial helpful ?