
C# EndsWith and LastIndexOf check the end string
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.
-
Related Reading
- C# Read and write to text file Newline, with one lin
- C# merge binary array(byte array)
- C# Winform button transparent background with proper
- C# float, double range, precision, definition and ty
- C# efficiency comparison of multiple strings concate
- C# date format and examples, with binding and ToStri
- Bubble sort algorithm example in C# and C (Ascending
- C# Hashtable create, add, update, remove and removed
- C# judge whether cookies are disabled on the client
- C# remove first or last character from string
- C# get url, domain, absolute, relative and physical
- C# if else vs switch, which efficiency is high(multi