Efficient Trailing Substring Checks in C# with `String.EndsWith()`
Learn how to effectively check if a string ends with a specific substring using C#'s `String.EndsWith()` method. This tutorial covers different overloads, including case-sensitive and case-insensitive comparisons, providing practical examples for string manipulation and validation in your C# applications.
Checking for Trailing Substrings in C# with `String.EndsWith()`
Understanding `String.EndsWith()`
The C# `EndsWith()` method checks if a string ends with a specified substring. It's a simple yet useful method for validating strings or performing string comparisons. It's case-sensitive by default, but you can specify different comparison options.
`String.EndsWith()` Method Signatures
The `EndsWith()` method has several overloads to handle various scenarios:
public bool EndsWith(string value);
: Checks if the string ends with the specified value (case-sensitive).public bool EndsWith(string value, StringComparison comparisonType);
: Allows you to specify the comparison type (case-sensitive or insensitive, etc.).public bool EndsWith(string value, bool ignoreCase, CultureInfo culture);
: Provides more fine-grained control over case-insensitive comparisons using culture-specific rules.
Example: Using `String.EndsWith()`
This example demonstrates checking if a string ends with specific substrings. The output shows whether or not each of the example substrings exists at the end of the original string. The `EndsWith()` method is case-sensitive by default.
C# Code
using System;
public class EndsWithExample {
public static void Main(string[] args) {
string str = "Hello";
string str2 = "llo";
string str3 = "World";
Console.WriteLine(str.EndsWith(str2)); // Output: True
Console.WriteLine(str.EndsWith(str3)); // Output: False
}
}
Conclusion
The `String.EndsWith()` method is a valuable tool for string manipulation in C#. Its different overloads offer flexibility in performing case-sensitive and case-insensitive comparisons, and you should select the appropriate overload for your needs.