截取指定长度字符串
2009-08-27 19:21
239 查看
方法1:
方法2:
方法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"
);
http://hi.baidu.com/linrao/blog/item/82b9178a921cf11ac8fc7ada.html
//截取指定长度字符串 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
相关文章推荐
- 高效率的C#截取指定长度字符串,大于指定长度的,在末尾显示指定字符,默认为"..."
- 不区分汉字还是英文和数字,按指定字节长度截取字符串
- 在C#中截取指定长度的中文字符串.
- 用C#截取指定长度的中英文混合字符串
- freemaker页面中截取指定长度的字符串,超出长度的部分用…替代
- c#截取指定字节长度的字符串
- [导入]用C#截取指定长度的中英文混合字符串 改进版
- 长字符串按指定长度截取的实现方法
- jQuery截取指定长度字符串代码
- 自动截取指定长度的字符串
- 在C#中截取指定长度的中文字符串
- 用C#截取指定长度的中英文混合字符串 改进版
- asp.net 安全的截取指定长度的html或者ubb字符串
- [Android]TextUtils.ellipsize()截取指定长度字符串(附图文混排)
- 将字符串截取为指定长度的几段的做法
- 从一个包含汉字和其他字符的字符串中截取指定字节长度的字符串,不可以出现中文乱码
- Java 按指定长度截取字符串,考虑全角半角
- C#截取指定长度中英文字符串方法
- 高效率的C#截取指定长度字符串,大于指定长度的,在末尾显示指定字符,默认为"..."
- c#的中英文混合字符串截取指定长度,startidx从0开始