求中英文混合字符串长度,中英文混合字符串截取(汉字2个字节,字母数字等1个字节),字符转ASCII码,ASCII码转字符...

/// <summary> /// 求字符串的实际长度(汉字2个字节,外语字符1个字节) /// </summary> /// <param name="str"></param> /// <returns></returns> public static int Length(string str) { int len = 0; char[] arr = str.ToCharArray(); for (int i = 0; i < arr.Length; i++) { //汉字 if (Asc(arr[i].ToString()) == -1) len += 2; else len += 1; } return len; } /// <summary> /// 重写截取字符串方法,这里的长度是字节数(汉字2个字节,外语字符1个字节) /// </summary> /// <param name="str"></param> /// <param name="length">截取长度(这里的长度是字节数,汉字2个字节,外语字符1个字节)</param> /// <returns></returns> public string Substring(string str, int length) { int len = 0; char[] arr = str.ToCharArray(); string strReturn = string.Empty; //参数检查 if (length > Length(str)) length = Length(str); for (int i = 0; i < arr.Length; i++) { //汉字 if (Asc(arr[i].ToString()) == -1) len += 2; else len += 1; if (len > length) break; strReturn += arr[i].ToString(); } return strReturn; } /// <summary> /// 字符转ASCII码,如果未能转换为ASCII码返回-1 /// </summary> /// <param name="character"></param> /// <returns></returns> public static int Asc(string character) { if (character.Length == 1) { //因为汉字和?都被转换为63,所以?进行提前处理 if (character == "?") return 63; System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding(); int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0]; //如果未能转换为ASCII码(暂且认为为汉字) if (intAsciiCode == 63) return -1; return (intAsciiCode); } else { throw new Exception("Character is not valid."); } } /// <summary> /// ASCII码转字符 /// </summary> /// <param name="asciiCode"></param> /// <returns></returns> public static string Chr(int asciiCode) { if (asciiCode >= 0 && asciiCode <= 255) { System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding(); byte[] byteArray = new byte[] { (byte)asciiCode }; string strCharacter = asciiEncoding.GetString(byteArray); return (strCharacter); } else { throw new Exception("ASCII Code is not valid."); } }

关于ASCII码的转换参考:

http://blog.csdn.net/ldw701/archive/2006/06/01/767875.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值