using System;
class EditDistrictCode
{
public static void Main(string[] args)
{
while(true)
{
Console.Write("请输入一个或多个汉字(按\"E\"退出):");
string inputString = Console.ReadLine();
if(inputString.ToUpper() == "E")
{
break;
}
else
{
if(CheckInput(inputString))
{
Console.WriteLine(MultiTextToQwm(inputString));
}
else
{
Console.WriteLine("你输入了非法字符!");
}
}
}
}
//检查输入的是否为汉字
public static bool CheckInput(string inputString)
{
bool result = true;
char[] textArray = inputString.ToCharArray();
foreach (char cha in textArray)
{
//只要有一个不符合条件,结果即为假(汉字的ASCII在0x4e00至0x9fa5之间)
if (!(cha >= 0x4e00 && cha <= 0x9fa5))
{
result = false;
}
}
return result;
}
//单个汉字处理
public static string OneTextToQwm(string character)
{
//将汉字的机器码取出放入字节数组中
byte[] bytes = System.Text.Encoding.Default.GetBytes(character);
//将机器码高字节部分放入highByte变量中,低字节部分放入lowByte中
int highByte = (int)(bytes[0]);
int lowByte = (int)bytes[1];
highByte -= 160;
lowByte -= 160;
//设置区码、位码,位置只有一位在前面补0
string highCode = highByte.ToString();
string lowCode = lowByte.ToString();
if (highCode.Length == 1)
{
highCode += "0";
}
if (lowCode.Length == 1)
{
lowCode += "0";
}
return character + highCode + lowCode;
}
//多个汉字处理
public static string MultiTextToQwm(string character)
{
string coding = null;
for (int i = 0; i < character.Length; i ++ )
{
coding +=OneTextToQwm(character.Substring(i,1));
}
return coding;
}
}
[此贴子已经被作者于2006-10-20 16:59:34编辑过]