下有字符串:
str="你好welcome"我想要前5个字节的字符,也就是"你好w"。请问如何处理?

解决方案 »

  1.   

    str = str.Substring(0, 5);
      

  2.   

    private static Encoding _encoding = System.Text.Encoding.GetEncoding("Shift_Jis");
    public static string SubstringByte(string text, int startIndex, int length)
    {
    byte[] bytes = _encoding.GetBytes(text) ;
    return _encoding.GetString(bytes, startIndex, length) ;
    }
      

  3.   

    /// <summary>
    /// 截取字符串(适用于中英文混合)
    /// </summary>
    /// <param name="str">原字符串</param>
    /// <param name="len">长度</param>
    /// <returns></returns>
    public static string CutString(string str,int len)
    {
    str = str.Trim();
    byte[] myByte = System.Text.Encoding.Default.GetBytes(str);   
    if(myByte.Length>len)
    {
    string result = "";
    for(int i=0;i<str.Length;i++)
    {
    byte[] tempByte=System.Text.Encoding.Default.GetBytes(result);
    if(tempByte.Length<len)
    {
    result += str.Substring(i,1);
    }
    else
    {
    break;
    }     
    }
    return result+"...";
    }
    else
    {
    return str;
    }
    }
      

  4.   

    刚刚上面的是日文系统的,简体中文是下面的
    private static Encoding _encoding = System.Text.Encoding.GetEncoding("GB18030");
    public static string SubstringByte(string text, int startIndex, int length)
    {
    byte[] bytes = _encoding.GetBytes(text) ;
    return _encoding.GetString(bytes, startIndex, length) ;
    }
      

  5.   

    这样的结果会是    “你好wel”
      

  6.   

    把Encoding换成unicode的public static string SubstringByte(string text, int index, int length)
    {
             if (text == null || text.Trim() == "" || index > length - 1)
             {
                  return text;
             }
             
    byte[] bytes = Encoding.Unicode.GetBytes(text);
    return Encoding.Unicode.GetString(bytes, index, length);
    }