獲取字符串的字節數

直接上代碼了

/** ======================================
 * Copyright (c) 2015, NSNG All Rights Reserved.
 * Date:2015年3月13日 下午1:56:22
 */
package test;

public class TestLen {

	public static void main(String[] args) {
		System.out.println(TestLen.getWordCount("a"));
		System.out.println(TestLen.getWordCount("啊"));
		System.out.println(TestLen.getWordCount("a啊"));
	}

	/**
	 * 獲取字符串字節數
	 */
	public static int getWordCount(String s) {
		int length = 0;
		for (int i = 0; i < s.length(); i++) {
			int ascii = Character.codePointAt(s, i);
			if (ascii >= 0 && ascii <= 255)
				length++;
			else
				length += 2;

		}
		return length;

	}

	/**
	 * [正則表達式]獲取字符字節數
	 */
	public static int getWordCountByReg(String s) {
		s = s.replaceAll("[^\\x00-\\xff]", "**");
		int length = s.length();
		return length;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章