java.lang.String.getBytes().lengthで文字列のバイト数を取得する
サンプルコード
package com.arkgame.study;
import java.io.UnsupportedEncodingException;
public class StrLenDemo {
public static void main(String[] args) {
String str = "東京";
try {
System.out.println("文字列のバイト数:" + str.getBytes().length);
System.out.println("UTF-8エンコード:" + str.getBytes("UTF-8").length);
System.out.println("Shift-JISエンコード:" + str.getBytes("Windows-31J").length);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
結果
文字列のバイト数:6
UTF-8エンコード:6
Shift-JISエンコード:4