您的位置:首页 > 其它

截取指定长度字符串

2009-08-27 19:21 239 查看
方法1:

//截取指定长度字符串
public static string getStr(string s,int l)
{
string temp=s;
if(Regex.Replace(temp,"[/u4e00-/u9fa5]","zz",RegexOptions.IgnoreCase).Length<=l)
{
return temp;
}
for(int i=temp.Length; i>=0; i--)
{
temp=temp.Substring(0,i);
if(Regex.Replace(temp,"[/u4e00-/u9fa5]","zz",RegexOptions.IgnoreCase).Length<=l-3)
{
return temp+"...";
}
}
return "";
}


方法2:
///   <summary>
///   将指定字符串按指定长度进行剪切,
///   </summary>
///   <param   name= "oldStr "> 需要截断的字符串 </param>
///   <param   name= "maxLength "> 字符串的最大长度 </param>
///   <param   name= "endWith "> 超过长度的后缀 </param>
///   <returns> 如果超过长度,返回截断后的新字符串加上后缀,否则,返回原字符串 </returns>
public static string StringTruncat(string oldStr, int maxLength, string endWith)
{
if (string.IsNullOrEmpty(oldStr))
//   throw   new   NullReferenceException( "原字符串不能为空 ");
return oldStr + endWith;
if (maxLength < 1)
throw new Exception("返回的字符串长度必须大于[0] ");
if (oldStr.Length > maxLength)
{
string strTmp = oldStr.Substring(0, maxLength);
if (string.IsNullOrEmpty(endWith))
return strTmp;
else
return strTmp + endWith;
}
return oldStr;
}


方法3:
private static byte
[] SourceStr_Bytes;

private static byte
[] CutStr_Bytes = new byte[42];

private static byte
[] CutStr_Bytes1;

private static int
Bytes_Count = 0;

private static string
CutedStr;

private static
Encoding
myEncoding = Encoding
.GetEncoding("GB2312"
);
/// <summary>
/// 截取字符长度,以位长截取,并指定截取位长.不足指字位长,则不截取.原样返回.
/// </summary>
/// <param name="SourceString">被截取源字符串</param>
/// <param name="CutLeng">指定要截取位长长度</param>
/// <returns>返回截取后字符串</returns>
public static string CutStringByByBytes(string SourceString,int CutLeng)
{
CutStr_Bytes1 = new byte[CutLeng];
SourceStr_Bytes = myEncoding.GetBytes(SourceString);
Bytes_Count = SourceStr_Bytes.Length;
if (Bytes_Count > CutLeng)
{
Array.Copy(SourceStr_Bytes, 0, CutStr_Bytes1, 0, CutLeng);
CutedStr = myEncoding.GetString(CutStr_Bytes1);
CutedStr = CutedStr.Substring(0, CutedStr.Length - 1) + "...";
return CutedStr;
}
return SourceString;
}

http://hi.baidu.com/linrao/blog/item/82b9178a921cf11ac8fc7ada.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: