35
技術社區[雲棲]
C#/asp.net中如何將數字全角半角互轉
C#/asp.net中如何將數字全角半角互轉?
//用戶公用靜態類,包含公用靜態方法
///
<summary>
///
用戶公用靜態類,包含公用靜態方法
///
</summary>
public
static class UserPublicStaticMethod
{
//把字母,數字由半角轉化為全角
/// <summary>
/// 把字母,數字由半角轉化為全角
/// </summary>
/// <param name="str">原始字符串</param>
/// <returns>全角字符串</returns>
public static string ChangeStrToSBC(string str)
{
char[] c = str.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
if (b.Length == 2)
{
if (b[1] == 0)
{
b[0] = (byte)(b[0] - 32);
b[1] = 255;
c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
}
}
}
//半角
string strNew = new string(c);
return strNew;
}
//將字母,數字由全角轉化為半角
/// <summary>
/// 將字母,數字由全角轉化為半角
/// </summary>
/// <param name="str">原始字符串</param>
/// <returns>半角字符串</returns>
public static string ChangeStrToDBC(string str)
{
string s = str;
char[] c = s.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
if (b.Length == 2)
{
if (b[1] == 255)
{
b[0] = (byte)(b[0] + 32);
b[1] = 0;
c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
}
}
}
//半角
string news = new string(c);
return news;
}
}
最後更新:2017-04-02 06:51:42