字符串截取,一个中文算两个字符

//截取字符串
        public static string LeftStr(string str, int len)
        {
            if (str.Length == 0) return str;

            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0;
            string tempString = "";
            byte[] s = ascii.GetBytes(str);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }

                try
                {
                    tempString += str.Substring(i, 1);
                }
                catch
                {
                    break;
                }

                if (tempLen > len)
                    break;
            }
            return tempString;
        }

代码2

//截取字符串
        public static string Cut_Str(String iStr,int len,String ended) {
            if (String.IsNullOrEmpty(iStr)) return String.Empty;

            byte[] bytes = Encoding.Unicode.GetBytes(iStr);
            int j = 0;
            int i = 0;
            for (; i < bytes.Length && j < len; i++) {
                if (i % 2 == 0)
                    j++;
                else if (bytes[i] > 0) //汉字
                    j++;
            }

            if (i % 2 == 1) {
                if (bytes[i] > 0)
                    i--;
                else
                    i++;
            }
            if (j <= (len - 1)) ended = String.Empty;
            return Encoding.Unicode.GetString(bytes, 0, i) + ended;
        }

你可能感兴趣的:(C#字符串截取)