/// 任意字符串/// 任意字符串/// 字符串全角字符串/// 半角字符串
public class StringHelper
{
#region 全角半角互相转换
/// <summary>
/// 转全角的函数(SBC case)
/// </summary>
/// <param name=”str”>任意字符串</param>
/// <returns>全角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
public static string ToSBC(string str)
{
//半角转全角:
char[] c = str.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 32)
{
c[i] = (char)12288;
continue;
}
if (c[i] < 127)
c[i] = (char)(c[i] + 65248);
}
return new string(c);
}
/// <summary> 转半角的函数(DBC case) </summary>
/// <param name=”str”>任意字符串</param>
/// <returns>半角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
public static string ToDBC(string str)
{
char[] c = str.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288)
{
c[i] = (char)32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char)(c[i] – 65248);
}
return new string(c);
}
#endregion 全角半角互相转换
#region 按照字节数截取字符串 一个汉字算2个字节
/// <summary>
/// 按照字节截取字符串 一个汉字算2个字节
/// </summary>
/// <param name=”str”>字符串</param>
/// <param name=”length”>截取数量,单位:字节</param>
/// <param name=”flag”>返回字符串 是否带省略号;true 带 false 不带</param>
/// <returns></returns>
public static string Substring(string str, int length, bool flag = true)
{
byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
string resultStr = str;
if (bytes.Length > length)
{
resultStr = “”;
for (int i = 0; i < str.Length; i++)
{
byte[] b = System.Text.Encoding.Default.GetBytes(resultStr);
if (b.Length < length)
{
resultStr += str.Substring(i, 1);
}
else
{
if (flag)
{
resultStr += “…”;
}
break;
}
}
}
return resultStr;
}
#endregion 按照字节数截取字符串 一个汉字算2个字节
#region Unicode 编码 解码
/// <summary>
/// unicode 编码;例:((int)’以’).ToString(“x”)
/// </summary>
/// <param name=”str”></param>
/// <returns></returns>
public static string UnicodeDecode(string str)
{
string outStr = “”;
if (str != “”)
{
for (int i = 0; i < str.Length; i++)
{
outStr += @”u” + ((int)str[i]).ToString(“x”);
}
}
return outStr;
}
/// <summary>
/// Unicode解码 按照u分割;例如:(char)int.Parse(“4ee5”, System.Globalization.NumberStyles.HexNumber)
/// </summary>
/// <param name=”str”></param>
/// <returns></returns>
public static string UnicodeEncode(string str)
{
MatchCollection mc = Regex.Matches(str, @”\u([w]{2})([w]{2})”, RegexOptions.Compiled | RegexOptions.IgnoreCase);
foreach (Match m in mc)
{
string hz = ((char)int.Parse(m.Groups[1].Value + m.Groups[2].Value, System.Globalization.NumberStyles.HexNumber)).ToString();
str = str.Replace(m.ToString(), hz);
}
return str;
}
#endregion Unicode 编码 解码
}
原文地址:https://blog.csdn.net/vbloveshllm/article/details/136064886
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_68155.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!