C# String EndsWith() Method
The EndsWith()
method in C# is a string instance method that is used to determine whether a string ends with a specified suffix. It returns a Boolean value indicating whether the string ends with the suffix.
Here is an example of using the EndsWith()
method:
string str = "The quick brown fox jumps over the lazy dog"; string suffix = "dog"; if (str.EndsWith(suffix)) { Console.WriteLine("The string ends with the suffix."); } else { Console.WriteLine("The string does not end with the suffix."); }
In this example, we check whether the string str
ends with the suffix "dog" using the EndsWith()
method. Since the string ends with the suffix, the Console.WriteLine()
statement prints "The string ends with the suffix." to the console.
The EndsWith()
method has overloads that allow you to perform a case-insensitive search or to specify a culture-specific comparison. Here is an example of a case-insensitive search:
string str = "The quick brown fox jumps over the lazy dog"; string suffix = "DOG"; if (str.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("The string ends with the suffix."); } else { Console.WriteLine("The string does not end with the suffix."); }
In this example, we use the StringComparison.OrdinalIgnoreCase
argument to perform a case-insensitive search for the suffix "DOG". Since the string ends with the suffix, the Console.WriteLine()
statement prints "The string ends with the suffix." to the console.
Note that the EndsWith()
method returns true
if the specified suffix is an empty string, since an empty string is considered to be a suffix of any other string.