Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C# String - EndsWith() Method



The C# String EndsWith() method is used to check whether this string ends with the specified string/character or not.

If the value is null this method throw an ArgumentNullException.

Syntax

Following is the syntax of the C# string EndsWith() method −

public bool EndsWith (char/string value);

Parameters

This method accepts only one parameter, either character or string. It compares the character to the character at the end of this object or the string to the substring at the end of this object.

Return value

This method returnstrue if the value matches the end of this object or instance; otherwise,it returns false.

Example 1: Check for The Characters

Following is the basic example of theEndsWith()method to check whether the specified character is available at the end of the string −

    
using System;
class Program {
   static void Main() {
      string str = "Hello, tutorialspoint";
      bool res = str.EndsWith('t');
      Console.WriteLine(res);
   }
}

Output

Following is the output −

True

Example 2: Check for The String

Let us look another example of the EndsWith() method. Here, we check for a string whether it is available at the end of the string or not −

using System;
class Program {
   static void Main() {
      string str = "Hello, tutorialspoint";
      bool res = str.EndsWith("point");
      Console.WriteLine("The string is available at the end: " + res);
   }
}

Output

Following is the output −

The string is available at the end: True

Example 3: If Character is Not Present at The End

In this example, we use the EndsWith() method to check a character is present at the end of the string. If not, then this method returns false −

using System;
class Program {
   static void Main() {
      string str = "Hello, tutorialspoint";
      bool res = str.EndsWith('P');
      Console.WriteLine("The character is available at the end: " + res);
   }
}

Output

Following is the output −

The character is available at the end: False

Example 4: If a String Ends with a Specific Substring

The below example uses the conditional statement to display the statement if the string ends with a specific substring −

using System;
class Program {
   static void Main() {
      string str = "Hello, tutorialspoint";
      bool res = str.EndsWith("spoint");
      Console.Write(res == true 
         ? "The specified string is available in this string" 
         : "The specified string is not available in the string");
   }
}

Output

Following is the output −

The specified string is available in this string
csharp_strings.htm
Advertisements