zoukankan      html  css  js  c++  java
  • 字符串劈分(含中文)

    题目:从含有中文字符的长度为N的字符串中截取M个字符,中文字符不能被分成两半。如从"我a爱中华abc我爱中国def,我ABC汉" 中取4个字符结果应该为"我a",而不是"我a爱"。

    TIP:

    * 将字符转码为GBK[一个中文包含两个字符且均小于0]
    * 标识符标记前一个字节小于0作为辅助判断依据
    * 当前字节小于0且前一次小于0【标识符判断】则为一个中文, 否则改变标识符的状态

    public static int trimGBK(byte[] buf, int n) {
    	int num = 0;
    	boolean bChineseFirstHalf = false;
    	for (int i = 0; i < n; i++) {
    		if (buf[i] < 0 && !bChineseFirstHalf) {
    			bChineseFirstHalf = true;
    		} else {
    			num++;
    			bChineseFirstHalf = false;
    		}
    	}
    	return num;
    }
    

      

  • 相关阅读:
    C语言01
    C++面试总结更新
    Python网络爬虫与信息提取02
    Self-Driving Car 01
    Python网络爬虫与信息提取01
    Python-03
    Shell
    Python-05
    Python-04
    Python-02
  • 原文地址:https://www.cnblogs.com/cugb-2013/p/3662435.html
Copyright © 2011-2022 走看看