c#实现的去掉头或尾部的指定字符串
用的是扩展方法实现,引用了这段代码所在的类时,直接可以用
代码如下:
/// <summary>
/// 替换字符串起始位置(开头)中指定的字符串
/// </summary>
/// <param name="s">源串</param>
/// <param name="searchStr">查找的串</param>
/// <param name="replaceStr">替换的目标串</param>
/// <returns></returns>
public static string TrimStarString(this string s, string searchStr, string replaceStr)
{
var result = s;
try
{
if (string.IsNullOrEmpty(result))
{
return result;
}
if (s.Length < searchStr.Length)
{
return result;
}
if (s.IndexOf(searchStr, 0, searchStr.Length, StringComparison.Ordinal) > -1)
{
result = s.Substring(searchStr.Length);
}
return result;
}
catch (Exception e)
{
return result;
}
}
/// <summary>
/// 替换字符串末尾位置中指定的字符串
/// </summary>
/// <param name="s">源串</param>
/// <param name="searchStr">查找的串</param>
/// <param name="replaceStr">替换的目标串</param>
public static string TrimEndString(this string s, string searchStr, string replaceStr)
{
var result = s;
try
{
if (string.IsNullOrEmpty(result))
{
return result;
}
if (s.Length < searchStr.Length)
{
return result;
}
if (s.IndexOf(searchStr, s.Length - searchStr.Length, searchStr.Length, StringComparison.Ordinal) > -1)
{
result = s.Substring(0, s.Length - searchStr.Length);
}
return result;
}
catch (Exception e)
{
return result;
}
}