如何截取字符串,只显示前面几个,多截少不补要考虑到二个英文算一个汉字

解决方案 »

  1.   

    看你是想按字符截取还是按字节截取,按字符取直接SubString就行了,按字节的话,就先将字符串转成字节数组,截取前面的若干个,然后再转成字符串,这时要考虑半个汉字的问题。
      

  2.   

    public static string StringCut( string strInput , string strEnd , int intLen )
    {
    strInput = strInput.Trim() ;
    int byteLen = Encoding.Default.GetByteCount( strInput ) ;
    if ( byteLen > intLen )
    {
    string resultStr = "" ;
    for ( int i = 0 ; i < strInput.Length ; i++ )
    {
    if ( Encoding.Default.GetByteCount( resultStr ) < intLen - strEnd.Length )
    {
    resultStr += strInput.Substring( i , 1 ) ;
    }
    else
    {
    break ;
    }
    }
    return resultStr + strEnd ;
    }
    else
    {
    return strInput ;

    }
    }
      

  3.   

    你直接substring就行了, 应为.Net中字符是会自动判断宽字还是普通的字的
    如果你是要根据显示的长度来截字符串, 那就要用System.Text.Encoding.GetEncoding("gb2312").GetByteCount来数字节数
      

  4.   

    string str ="a你?bc我123";
                byte[] strb = Encoding.Default.GetBytes(str);
                int cnt =4;
                byte[] subb = new byte[cnt];
                Buffer.BlockCopy(strb, 0, subb, 0, cnt);
                string sub = Encoding.Default.GetString(subb);
                if ((subb[cnt-1]!='?') && (sub[sub.Length - 1] == '?'))
                    sub = sub.Substring(0, sub.Length - 1);
                Console.WriteLine(sub);