您的位置:首页 > 编程语言 > C#

C#中判断字符串是全角还是半角

2010-08-06 11:14 417 查看
全角是指用二个字节来表示的一个字符
半角是用一个字节来表示的一个字符


这样的话我们就可以用string.length 和System.text.Encoding.Default.GetByteCount来判断

其中string.length表示字符串的字符数,
System.text.Encoding.Default.GetByteCount表示字符串的字节数。

将全角的变为半角
string s="GBJ1—86";
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);

把字母,数字由半角转化为全角
public string ChangeStr( 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;
}

判断的方法一:
代码测试报告:只能对单个字符进行判断,如果出现"23" 判断结果是半角,忽略了后面的全角,如果需要判断就要遍历证字符串
string s = null;

s = "A";
MessageBox.Show(((s[0] > 255) ? "全角" : "半角") + " ASCII of " + Convert.ToInt32(s[0]).ToString("x").ToUpper());

s = "A";
MessageBox.Show(((s[0] > 255) ? "全角" : "半角") + " ASCII of " + Convert.ToInt32(s[0]).ToString("x").ToUpper());

//中文的Unicode大概是从4E00 到 9FA0,所以上例一个是0x41 一个是0xFF21

判断的方法二:
代码测试报告:只能对单个字符进行判断,如果出现"23" 判断结果是半角,忽略了后面的全角,如果需要判断就要遍历证字符串
if (checkString.Length == Encoding.Default.GetByteCount(checkString))
{
return true;
}
else
{
return false;
}

全角如下:
if (2 * checkString.Length == Encoding.Default.GetByteCount(checkString))
{
return true;
}
else
{
return false;
}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/foart/archive/2008/10/04/3014019.aspx

Example:

判断一个字符是全角还是半角(占一个字节还是两个字节

String source = "ls;;'立刻地方机十分kd 立刻地方";
int length = source.length();
for(int i=0;i<length;i++)
{
char c = source.charAt(i);
if (c > 255)
{
System.out.print("中文 ");
}
System.out.println(c);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: