3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scala: String.lengthがマルチバイトでどうなるか調べてみた

Posted at

シングルバイト

"a"の文字数は1になるはず

"a".length
//> res0: Int = 1

1でした

マルチバイト

"あ"の文字数は1になる? もしくは3?

"あ".length
//> res1: Int = 1

1でした。

Unicodeサロゲートペア

"?"の文字数は1? もしくは2? それとも4??

"?".length
//> res2: Int = 1

1でした…!

次は、NFC、NFDの違いも調べたい

参考までに他の言語も調べてみた

Java

class Untitled {
	public static void main(String[] args) {
		System.out.println("a".length()); // 1
		System.out.println("あ".length()); // 1
		System.out.println("?".length()); // 2
	}
}

JavaがScalaと違うということは、Scala側でサロゲートペアを吸収してるってことかな

PHP

<?php

var_dump(strlen("a")); // 1
var_dump(strlen("あ")); // 3
var_dump(strlen("?")); // 4

// マルチバイト対応関数
mb_internal_encoding("UTF-8");
var_dump(mb_strlen("a")); // 1
var_dump(mb_strlen("あ")); // 1
var_dump(mb_strlen("?")); // 1

Node.js

console.log("a".length); // 1
console.log("".length); // 1
console.log("?".length); // 2

Go

package main

func main() {
	println(len("a")) // 1
	println(len("あ")) // 3
	println(len("?")) // 4
}

Ruby

puts "a".length # 1
puts "あ".length # 3
puts "?".length # 4

Node.js、Go、Rubyもマルチバイト対応の関数があるかもしれないが、そこまでは調べてない。

3
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?