• C# 字符串转字节截取


    今天要截取一个文档,发现C#中substring默认是将汉字当一个字节来截取的,但是我需要把汉字按照2个字节来算。

    比如:

    str="雪洁hello"

    我想要前5个字节的字符,也就是"雪洁h"。

    如何处理?

    C#中substring默认是将汉字当一个字节来截取的,那么如何按字节数截取字符串?

    答案:

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Text;
      
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String str = "雪洁之家,xuejie's blog,你好,hello";
            TextBox1.Text = str.Substring(0, 8);
            TextBox2.Text = SubstringByte(str, 0, 8);
            TextBox3.Text = cutSubstring(str, 8);
            TextBox4.Text = SubstringByte(str, 0, 3);
            TextBox5.Text = cutSubstring(str, 3);
        }
      
        private static Encoding _encoding = System.Text.Encoding.GetEncoding("GB2312");
      
        //第一种方法
        private string SubstringByte(string text, int startIndex, int length)
        {
            byte[] bytes = _encoding.GetBytes(text);
            return _encoding.GetString(bytes, startIndex, length);
        }
      
        //第二种方法
        private string cutSubstring(string s, int length)
        {
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(s);
            int n = 0;  //  表示当前的字节数
            int i = 0;  //  要截取的字节数
            for (; i < bytes.GetLength(0) && n < length; i++)
            {
                //  偶数位置,如0、2、4等,为UCS2编码中两个字节的第一个字节
                if (i % 2 == 0)
                {
                    n++;      //  在UCS2第一个字节时n加1
                }
                else
                {
                    //  当UCS2编码的第二个字节大于0时,该UCS2字符为汉字,一个汉字算两个字节
                    if (bytes[i] > 0)
                    {
                        n++;
                    }
                }
            }
            //  如果i为奇数时,处理成偶数
            if (i % 2 == 1)
            {
                //  该UCS2字符是汉字时,去掉这个截一半的汉字
                if (bytes[i] > 0)
                    i = i - 1;
                //  该UCS2字符是字母或数字,则保留该字符
                else
                    i = i + 1;
            }
            return System.Text.Encoding.Unicode.GetString(bytes, 0, i);
        }
    }

    来源:https://www.cnblogs.com/xuejie/archive/2012/12/14/2818452.html

  • 相关阅读:
    Laex/Delphi-OpenCV
    webbrowser 防止读取 缓存
    tesnsorflow 版本安装错了。 可以这样删除。
    python中%代表什么意思?
    python 访问 网页 获得源码
    3.2.2 break 与 continue 语句
    3.2.1 for循环与while循环的基本语法
    3.2 循环结构
    3.1.2 选择结构的几种形式
    3.1.1 条件表达式
  • 原文地址:https://www.cnblogs.com/yu-shang/p/12197781.html
Copyright © 2020-2023  润新知