「Java入門」指定文字列のバイト数を取得するサンプル
書式
文字列.getBytes(“UTF-8").length
使用例
package com.arkgame.study;
import java.io.UnsupportedEncodingException;
public class ByteLenDemo {
private static String CodeSet = "UTF-8";
public static void main(String[] args) throws UnsupportedEncodingException {
String strA = "あいうえおあいうえお";
String strB = "study skill in arkgame.com";
String strC = "567890";
System.out.println("文字列Aのバイト数: " + getStrBytesLen(strA));
System.out.println("文字列Bのバイト数: " + getStrBytesLen(strB));
System.out.println("文字列Cのバイト数: " + getStrBytesLen(strC));
}
/**
*文字列のバイト数を返す
* @param target
* @return
* @throws UnsupportedEncodingException
*/
static int getStrBytesLen(String target) throws UnsupportedEncodingException {
int result;
result = target.getBytes(CodeSet).length;
return result;
}
}
package com.arkgame.study;
import java.io.UnsupportedEncodingException;
public class ByteLenDemo {
private static String CodeSet = "UTF-8";
public static void main(String[] args) throws UnsupportedEncodingException {
String strA = "あいうえおあいうえお";
String strB = "study skill in arkgame.com";
String strC = "567890";
System.out.println("文字列Aのバイト数: " + getStrBytesLen(strA));
System.out.println("文字列Bのバイト数: " + getStrBytesLen(strB));
System.out.println("文字列Cのバイト数: " + getStrBytesLen(strC));
}
/**
*文字列のバイト数を返す
* @param target
* @return
* @throws UnsupportedEncodingException
*/
static int getStrBytesLen(String target) throws UnsupportedEncodingException {
int result;
result = target.getBytes(CodeSet).length;
return result;
}
}
package com.arkgame.study; import java.io.UnsupportedEncodingException; public class ByteLenDemo { private static String CodeSet = "UTF-8"; public static void main(String[] args) throws UnsupportedEncodingException { String strA = "あいうえおあいうえお"; String strB = "study skill in arkgame.com"; String strC = "567890"; System.out.println("文字列Aのバイト数: " + getStrBytesLen(strA)); System.out.println("文字列Bのバイト数: " + getStrBytesLen(strB)); System.out.println("文字列Cのバイト数: " + getStrBytesLen(strC)); } /** *文字列のバイト数を返す * @param target * @return * @throws UnsupportedEncodingException */ static int getStrBytesLen(String target) throws UnsupportedEncodingException { int result; result = target.getBytes(CodeSet).length; return result; } }
実行結果
文字列Aのバイト数: 30
文字列Bのバイト数: 26
文字列Cのバイト数: 6