EndsWith和LastIndexOf判断结尾字符
有的时候需要判断字符以什么字符结尾,在 C# 中,有一个专门判断字符串结尾字符的方法 EndsWith(),可能大多数使用过 C# 编程的用户都使用过;然而除了 EndsWith() 方法外,还可以使用 LastIndexOf() 方法判断。
两种方法都很简单,并且执行效率也相当,可根据方便性和习惯自由选用,以下是两种方法具体判断字符串结尾字符的方法。
一、EndsWith判断结尾字符的方法
/// <summary>
/// EndsWith()方法判断结尾字符
/// </summary>
/// <param name="endStr">待判断结尾字符(串)</param>
/// <returns>真:以传入的字符结束,反之为假</returns>
private bool EndsWithJudge(string endStr)
{
string str = "使用EndsWith()判断结尾字符";
if(str.EndsWith(endStr))//判断结尾字符
return true;
else
return false;
}
调用:
EndsWithJudge("判断");
二、LastIndexOf判断结尾字符的方法
/// <summary>
/// LastIndexOf()方法判断结尾字符
/// </summary>
/// <param name="endStr">待判断结尾字符(串)</param>
/// <returns>真:以传入的字符结束,反之为假</returns>
private bool LastIndexOfJudge((string endStr)
{
string str = "使用LastIndexOf()判断结尾字符";
if(str.LastIndexOf(endStr) == str.Length - endStr.Length)//判断结尾字符
return true;
else
return false;
}
调用:
if (LastIndexOfJudge(("尾字符"))
Response.Write("<br />真");
else
Response.Write("<br />假");
结果返回:真
以上代码都通过 Visual Studio 测试,如果想测试,尤其是 LastIndexOf 判断方法,把方法复制到一个 cs 文件中,把调用代码放到载入方法即可测试。