现在的位置: 首页 > 综合 > 正文

.NET常用类与方法——截取指定长度的字符串并在末尾加入指定字

2012年01月25日 ⁄ 综合 ⁄ 共 533字 ⁄ 字号 评论关闭

/* *方法说明:截取指定长度的字符串并在末尾加入指定字符 *参数说明:oldStr为原字符串,maxLength为截取长度,endWith为在末尾加入的字符 */ public static string StringTruncat(string oldStr, int maxLength, string endWith) { if (string.IsNullOrEmpty(oldStr))//原字符串为空时仅返回endWith { return oldStr + endWith; } if (maxLength<1)//指定长度必须大于0 { throw new Exception("返回的字符串长度必须大于0"); } if (oldStr.Length>maxLength)//原字符串长度大于截取长度时进行处理 { string strTmp = oldStr.Substring(0, maxLength);//对原字符串的子串进行处理 if (string.IsNullOrEmpty(endWith))//如果endWith为空返回子串 { return strTmp; } else return strTmp + endWith;//给子串加的末尾加上指定字符 } return oldStr;//原字符串长度小于等于截取长度时不作处理

抱歉!评论已关闭.