Skip to content

Instantly share code, notes, and snippets.

@masaru-b-cl
Created January 25, 2013 00:40
Show Gist options
  • Save masaru-b-cl/4630416 to your computer and use it in GitHub Desktop.
Save masaru-b-cl/4630416 to your computer and use it in GitHub Desktop.
文字列をShiftJISとして扱って先頭から指定したバイト数分切り出す。最後の文字がマルチバイト文字だった場合、切り落とす。
protected String substringByShiftJISBytesCount(String source, int bytesCount)
throws UnsupportedEncodingException {
if (source == null) return source;
byte[] bytes = source.getBytes("MS932");
if (bytes.length < bytesCount) return source;
String result = new String(bytes, 0, bytesCount, "MS932");
String last = result.substring(result.length() -1);
String lazt = new String(last.getBytes("MS932"), "MS932");
if (!last.equals(lazt)) {
result = result.substring(0, result.length()-1);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment