C# EndsWith and LastIndexOf check the end string

Lionsure 2020-08-06 Original by the website

Sometimes it is necessary to check what character a string ends with. There is a special method EndsWith() to check it in C#, which may be used by most users who have used C# programming; however, except for the EndsWith() method, you can also use the LastIndexOf() method to check.

The two methods are very simple, and the execution efficiency is also equivalent. They can be freely selected according to convenience and habits. The following are two methods to specifically check the end character of a string.

 

1. C# EndsWith check the end string

/// <summary>
       /// EndsWith() method to check the end string
       /// </summary>
       /// <param name="endStr">End character(or string) to be checked</param>
       /// <returns>True: end with the character(or string) passed in, otherwise false</returns>

       private bool EndsWithCheck(string endStr)
       {
              string str = "String endswith c#";

       if(str.EndsWith(endStr))//Check the end character(or string)
                     return true;
              else
                     return false;
       }

Call:

EndsWithCheck("endswith");

 

 

2. C# LastIndexOf check the end string

/// <summary>
       /// The LastIndexOf() method checks the end string
       /// </summary>
       /// <param name="endStr">End character(or string) to be checked</param>
       /// <returns>True: end with the character(or string) passed in, otherwise false</returns>

       private bool LastIndexOfJudge(string endStr)
       {
              string str = "C# string lastindexof";

       if(str.LastIndexOf(endStr) == str.Length - endStr.Length)//Check the end character(or string)
                     return true;
              else
                     return false;
       }

Call:

if (LastIndexOfJudge("indexof"))
              Response.Write("<br />true");
       else
              Response.Write("<br />false");

Result returned: true

 

The above code has been tested by Visual Studio. If you want to test, especially the LastIndexOf method, copy it to a cs file and put the calling code in the loading method to test.