C# String EndsWith()

The String EndsWith() method checks whether the string ends with the specified string or not.

Example

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string text = "Ice cream";
    
// checks if text ends with cream bool result = text.EndsWith("cream");
Console.WriteLine(result); Console.ReadLine(); } } } // Output: True

EndsWith() Syntax

The syntax of the string EndsWith() method is:

EndsWith(string value, StringComparison comparisonType)

Here, EndsWith() is a method of class String.


EndsWith() Parameters

The EndsWith() method takes the following parameters:

  • value - string to compare to the substring at the end of the given string
  • comparisonType - determines how the given string and value are compared

EndsWith() Return Value

The EndsWith() method returns:

  • True - if the string ends with the given string
  • False - if the string doesn't end with the given string

Example 1: C# String EndsWith()

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string text = "Chocolate";
      bool result;
    
// checks if text ends with late result = text.EndsWith("late");
Console.WriteLine("Ends with late: " + result);
// checks if text ends with gate result = text.EndsWith("gate");
Console.WriteLine("Ends with gate: " + result); Console.ReadLine(); } } }

Output

Ends with late: True
Ends with gate: False

Here,

  • text.EndsWith("late") - returns True as text ends with "late"
  • text.EndsWith("gate") - returns False as text ends with "gate"

Example 2: C# String EndsWith() - Case Sensitivity

The EndsWith() method is case-sensitive. However, we can also ignore or consider letter cases.

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string text = "Ice cream";
      bool result;
    
// ignores case result = text.EndsWith("Cream", StringComparison.OrdinalIgnoreCase);
Console.WriteLine("Ends with Cream: " + result);
// considers case result = text.EndsWith("Cream", StringComparison.Ordinal);
Console.WriteLine("Ends with Cream: " + result); Console.ReadLine(); } } }

Output

Ends with Cream: True
Ends with Cream: False

Here,

  • StringComparison.OrdinalIgnoreCase - ignores letter case
  • StringComparison.Ordinal - considers letter case
Did you find this article helpful?