What is string.EndsWith() in C#?

Overview

In C#, the EndsWith() method is used to check if a specified string matches the end of a particular string or not. In other words, it checks if the specified string is what a particular string ends with.

Syntax

string1.EndsWith(string2)

Parameters

string1: This is the particular string that we want to check whether it ends with the specified string.

string2: This is the specified string. It is the string we want to check whether string1 ends with.

Return value

A Boolean value is returned. If string1 ends with string2, true is returned. Otherwise false is returned.

Code

In the code below, we will create some strings and see if they end with the specified strings that are passed to the EndsWith() method.

// create class
class EndsWithProgram
{
// main method
static void Main()
{
// define and initialize srings
string string1 = "education";
string string2 = "communication";
string string3 = "knowledge";
string string4 = "privilege";
// check if they end with
// specified strings below
bool a = string1.EndsWith("ion");
bool b = string2.EndsWith("ege");
bool c = string3.EndsWith("ion");
bool d = string4.EndsWith("iv");
// print returned values
System.Console.WriteLine(a);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
System.Console.WriteLine(d);
}
}

From the code above, only one True value is returned because education ends with ion and the other strings do not end with the string that was passed as a parameter.

Free Resources