获得定长字符串

        C#中的字符串是Unicode编码,length是Unicode的Char的个数。所以,假如一个字符串中中英文混杂,又想获得一个固定宽度的字符串,就比较麻烦。单纯转换成字节再截取难免会碰到半个汉字的问题。
        下面实现了这样的功能,返回固定字节长度的字符串,如果发生截断,后面补充2个或者3个“.”,根据截断点的位置决定。
        /// <summary>
        
/// 返回定长的字符串,如果发生截取,在后面补充两个或三个"."
        
/// Author:jetz
        
/// </summary>
        
/// <param name="ByteLen"></param>
        
/// <param name="str"></param>
        
/// <returns></returns>

        static public string GetFixupString(int ByteLen,string str)
        
{
            
if(System.Text.Encoding.Default.GetByteCount(str)<=ByteLen)return str;

            
for(int i=str.Length-1;i>0;i--)
            
{
                
int j=System.Text.Encoding.Default.GetByteCount(str.Substring(0,i));    //字节宽度
                if(j<=ByteLen-2)        //保证能显示".."
                {
                    
return str.Substring(0,i)+new string('.',ByteLen-j);
                }

            }

            
return "";
        }
posted @ 2005-11-18 16:36  jetz  阅读(933)  评论(0编辑  收藏  举报