问题是这样的,我想打印一个类似表单的东西,其中各项的长度不一样,要求要对齐显示,如下例:
一开始我用的是Console.WriteLine("{0, 9}{1, 20}....", code, name, ....),问题出现了:在“名称”这上栏里有中文字符,因为C#里用的是Unicode,所以一个汉字将会被格式函数识别成只占一个长度,最终导致不能对齐显示。。。。使用string的PadLeft等等函数问题也是一样的。。。。
可以使用下面这两个函数解决问题:
public static int TrueLength(string str)
{
int lenTotal = 0;
int n = str.Length;
string strWord = "";
int asc;
for (int i = 0; i < n; i++)
{
strWord = str.Substring(i, 1);
asc = Convert.ToChar(strWord);
if (asc < 0 || asc > 127)
{
lenTotal = lenTotal + 2;
}
else
{
lenTotal = lenTotal + 1;
}
}
return lenTotal;
}
public static string PadRightTrueLen(string strOriginal, int maxTrueLength, char chrPad, bool blnCutTail)
{
string strNew = strOriginal;
if (strOriginal == null || maxTrueLength <= 0)
{
strNew = "";
return strNew;
}
int trueLen = TrueLength(strOriginal);
if (trueLen > maxTrueLength)
{
if (blnCutTail)
{
for (int i = strOriginal.Length - 1; i > 0; i--)
{
strNew = strNew.Substring(0, i);
if (TrueLength(strNew) == maxTrueLength)
{
{
int lenTotal = 0;
int n = str.Length;
string strWord = "";
int asc;
for (int i = 0; i < n; i++)
{
strWord = str.Substring(i, 1);
asc = Convert.ToChar(strWord);
if (asc < 0 || asc > 127)
{
lenTotal = lenTotal + 2;
}
else
{
lenTotal = lenTotal + 1;
}
}
return lenTotal;
}
public static string PadRightTrueLen(string strOriginal, int maxTrueLength, char chrPad, bool blnCutTail)
{
string strNew = strOriginal;
if (strOriginal == null || maxTrueLength <= 0)
{
strNew = "";
return strNew;
}
int trueLen = TrueLength(strOriginal);
if (trueLen > maxTrueLength)
{
if (blnCutTail)
{
for (int i = strOriginal.Length - 1; i > 0; i--)
{
strNew = strNew.Substring(0, i);
if (TrueLength(strNew) == maxTrueLength)
{
break;
}
else if (TrueLength(strNew) < maxTrueLength)
{
strNew += chrPad.ToString();
break;
}
}
}
}
else// 填充
{
for (int i = 0; i < maxTrueLength - trueLen; i++)
{
strNew += chrPad.ToString();
}
}
return strNew;
}
else if (TrueLength(strNew) < maxTrueLength)
{
strNew += chrPad.ToString();
break;
}
}
}
}
else// 填充
{
for (int i = 0; i < maxTrueLength - trueLen; i++)
{
strNew += chrPad.ToString();
}
}
return strNew;
}
还有就是像SubString()这些函数在处理中文字符上面都是有问题的,SubString()可以用下面这个函数代替:
public static string getCountStr(string str, int count)
{
byte[] bwrite = Encoding.GetEncoding("GB2312").GetBytes(str.ToCharArray());
if (bwrite.Length >= count)
{
return Encoding.Default.GetString(bwrite, 0, count);
}
else
{
return Encoding.Default.GetString(bwrite);
}
}
{
byte[] bwrite = Encoding.GetEncoding("GB2312").GetBytes(str.ToCharArray());
if (bwrite.Length >= count)
{
return Encoding.Default.GetString(bwrite, 0, count);
}
else
{
return Encoding.Default.GetString(bwrite);
}
}
哎。。。。麻烦的Unicode吖。。。。