Skip to content

Instantly share code, notes, and snippets.

@furandon-pig
Created February 16, 2020 22:03
Show Gist options
  • Save furandon-pig/d9dba2943bc84a8a122705586509e2fe to your computer and use it in GitHub Desktop.
Save furandon-pig/d9dba2943bc84a8a122705586509e2fe to your computer and use it in GitHub Desktop.
Javaの文字列をbyte単位で比較するサンプルコードです。
/*
* 実行例:
* $ java Main
* s1= 日本語, length= 9
* s2= 日本語, length= 14
* oooooooooxxxxx
*/
public class Main {
public static void main(String... args) throws Exception {
// どちらもSystem.out.println()では「日本語」と表示される。
String s1 = "日本語";
String s2 = "日本語\b\b語";
if (args.length == 2) {
s1 = args[0];
s2 = args[1];
}
byte[] b1 = s1.getBytes("UTF-8");
byte[] b2 = s2.getBytes("UTF-8");
System.out.println("s1= " + s1 + ", length= " + b1.length);
System.out.println("s2= " + s2 + ", length= " + b2.length);
int size = (b1.length > b2.length) ? b1.length : b2.length;
for (int i = 0; i < size; i++) {
// 比較する2つのbyte配列のうち、どちらか一方が配列サイズよりも大きい場合か、
// byteの値が一致しない場合は"x"を表示する。
if ((b1.length <= i || b2.length <= i) || b1[i] != b2[i]) {
System.out.print("x");
} else {
System.out.print("o");
}
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment