C# String EndsWith

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

Introduction to the C# String EndsWith() method

The String EndsWith() method allows you to check if the end of a string matched a specified string, considering the culture during comparison.

The following shows the syntax of the EndsWith() method:

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

The EndsWith() method accepts a parameter value that represents the string to match. It returns true if the end of the current string matches the string value or false otherwise.

For example, the following uses the EndsWith() method to check if the string "To live or not to live" ends with the string "To live":

using static System.Console;

var message = "To live or not to live";
var result = message.EndsWith("to live");

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

Output:

TrueCode language: C# (cs)

The EndsWith() method returns true as expected.

The following example uses the EndsWith() method to check if the string "To live or not to live" ends 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.EndsWith("To Live");
WriteLine(result);Code language: C# (cs)

Output:

FalseCode language: C# (cs)

In this example, the EndsWith() method returns false because it compares strings case-sensitively.

To specify the comparison rules, you use the following overload of the EndsWith() method:

public bool EndsWith (
   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 EndsWith compare the strings.

For example, the following program illustrates how to use the EndsWith() method to check if a string ends with another string case-insensitively using the StringComparison.OrdinalIgnoreCase option:

using static System.Console;

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

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

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

Output:

TrueCode language: C# (cs)

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

public bool EndsWith (
   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 string. If the culture is null, the method uses the current culture.

Summary

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