C# 字符串截取(包括汉字)

来源:互联网 发布:sql 拆分字符串 编辑:程序博客网 时间:2024/05/16 04:42

private void GetSubString()
        {

            //截取的长度
            int count = 0;
            if (!string.IsNullOrEmpty(txtCount.Text))
            {
                count = Convert.ToInt32(txtCount.Text);
            }

            if (count >= 2)
            {

                //将截取的内容转化为byte
                byte[] content = System.Text.Encoding.Default.GetBytes(txtContent.Text);

                //将截取后的内容放到临时数组中

                byte[] temp = new byte[] { content[count - 1] };

                //将截取后的内容转化为字符串

                string strTemp = System.Text.Encoding.Default.GetString(temp);

                //判断字符串截取是否正确
                if (!txtContent.Text.Contains(strTemp))
                {
                    temp = new byte[] { content[count - 2], content[count - 1] };
                    strTemp = System.Text.Encoding.Default.GetString(temp);
                    if (!txtContent.Text.Contains(strTemp))
                    {
                        count++;
                    }
                }

                byte[] showContent = new byte[count];
                for (int i = 0; i < count; i++)
                {
                    showContent[i] = content[i];
                }

                lblShow.Text = System.Text.Encoding.Default.GetString(showContent);
                lblCount.Text = count.ToString();
            }
            else
            {
                lblShow.Text = txtContent.Text.Substring(0, count);
                lblCount.Text = count.ToString();
            }
        }