In C#, the EndsWith()
method is used to determine whether a string instance ends with a specified suffix. It returns a boolean value indicating the result of the comparison.
Here’s the syntax of the EndsWith()
method:
public bool EndsWith(string value)
The EndsWith()
method is called on a string instance and takes a single parameter value
, which is the suffix you want to check against the end of the string. It returns true
if the string ends with the specified suffix; otherwise, it returns false
.
Here’s an example usage of the EndsWith()
method:
string str = "Hello, world!"; bool endsWithWorld = str.EndsWith("world!"); Console.WriteLine(endsWithWorld); // Output: True bool endsWithGoodbye = str.EndsWith("goodbye!"); Console.WriteLine(endsWithGoodbye); // Output: False
In the example above, the EndsWith()
method is used to check if the string str
ends with the suffix “world!”. The first Console.WriteLine()
statement outputs True
because the string does end with the specified suffix. The second Console.WriteLine()
statement outputs False
because the string does not end with the suffix “goodbye!”.
Note that the EndsWith()
method performs a case-sensitive comparison by default. If you want to perform a case-insensitive comparison, you can use an overload of the method that accepts a StringComparison
parameter. For example:
string str = "Hello, world!"; bool endsWithWorldIgnoreCase = str.EndsWith("WORLD!", StringComparison.OrdinalIgnoreCase); Console.WriteLine(endsWithWorldIgnoreCase); // Output: True
In this case, the EndsWith()
method performs a case-insensitive comparison by passing StringComparison.OrdinalIgnoreCase
as the second argument.
C# String EndsWith() Method Example:
Certainly! Here’s an example that demonstrates the usage of the EndsWith()
method in C#:
string str = "Hello, world!"; bool endsWithWorld = str.EndsWith("world!"); if (endsWithWorld) { Console.WriteLine("The string ends with 'world!'"); } else { Console.WriteLine("The string does not end with 'world!'"); }
In this example, we have a string str
containing the value “Hello, world!”. The EndsWith()
method is called on the str
string instance with the argument “world!”. The method checks whether the string ends with the specified suffix.
If str
ends with the suffix “world!”, the endsWithWorld
variable will be true
, and the program will output “The string ends with ‘world!'” to the console. Otherwise, if the string does not end with the suffix “world!”, the endsWithWorld
variable will be false
, and the program will output “The string does not end with ‘world!'” to the console.
You can run this code in a C# environment (e.g., a console application) to see the output for yourself.