Uncover the Power of String EndsWith() in C#

When working with strings in C#, understanding how to effectively use the EndsWith() method is crucial. This powerful tool allows you to determine whether a string ends with a specified substring, making it an essential component of any C# developer’s toolkit.

The Anatomy of EndsWith()

The EndsWith() method is a part of the String class, and its syntax is straightforward: string.EndsWith(value, comparisonType). But what do these parameters mean?

  • value represents the string you want to compare to the substring at the end of your given string.
  • comparisonType determines how the strings are compared. This can be set to ignore or consider letter case, giving you greater control over your results.

What to Expect: The Return Value

So, what does the EndsWith() method return? It’s simple:

  • True if the string ends with the specified substring.
  • False if it doesn’t.

Putting EndsWith() to the Test

Let’s see this method in action. Consider the following examples:

Example 1: Basic EndsWith() Usage

Suppose we have a string text with the value “I’m late”. If we call text.EndsWith("late"), the method returns True, because the string indeed ends with “late”. However, if we call text.EndsWith("gate"), it returns False, since the string doesn’t end with “gate”.

Example 2: Case Sensitivity and Beyond

But what about case sensitivity? By default, the EndsWith() method is case-sensitive. To change this behavior, we can use the StringComparison.OrdinalIgnoreCase parameter to ignore letter case or StringComparison.Ordinal to consider it.

In our example, if we call text.EndsWith("LATE", StringComparison.OrdinalIgnoreCase), the method returns True, even though the original string was in lowercase. This demonstrates the flexibility of the EndsWith() method in handling different comparison scenarios.

Leave a Reply

Your email address will not be published. Required fields are marked *