18
19

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.

Ojbective-Cで絵文字を見た目通りにカウントする

Last updated at Posted at 2015-04-22

Repository

NSString-ActualLength
MIT LICENSE.

Issue

NSString lengthは絵文字を含むとカウントが予期せぬ値になる。

obj-c

NSLog(@"string: %@ length: %ld", str, [str length]);

output

xctest[-] string: 🔴🔴🔴🔴🔴 length: 10
xctest[-] string: 👦 length: 2
xctest[-] string: 👦👦🏿 length: 6
xctest[-] string: 👦🏼👦🏿 length: 8
xctest[-] string: 👨‍👩‍👧‍👦 length: 11
xctest[-] string: 👦He▶️♈️llo👦🏼🔴👦🏿🇨🇱🇨🇳🇨🇴🇩🇰🇫 length: 39
xctest[-] string: Hello World! length: 12
xctest[-] string: 🇦🇺🇦🇹🇧🇪🇧🇷🇨🇦🇨🇱🇨🇳🇨🇴🇩🇰🇫🇮 length: 40
xctest[-] string: 1⃣➡️▶️♈️🆗🆖🅰🆘✅㊗️ length: 19

Action

  • Regional Character(0xdde6 - 0xddff)のスキップ
  • Skin tone modifier(0xdffb - 0xdfff)のスキップ
  • Variation selector(0xfe00 - 0xfe0f)のスキップ
  • Zero-width Joiner(0x200d)のスキップ
  • 上記のカウントに伴うsubstring
NSLog(@"string: %@ length: %ld", str, [str actualLength]);
xctest[] string: 🔴🔴🔴🔴🔴 length: 5
xctest[] string: 👦 length: 1
xctest[] string: 👦👦🏿 length: 2
xctest[] string: 👦🏼👦🏿 length: 2
xctest[] string: 👨‍👩‍👧‍👦 length: 4
xctest[] string: 👦He▶️♈️llo👦🏼🔴👦🏿🇨🇱🇨🇳🇨🇴🇩🇰🇫 length: 16
xctest[] string: Hello World! length: 12
xctest[] string: 🇦🇺🇦🇹🇧🇪🇧🇷🇨🇦🇨🇱🇨🇳🇨🇴🇩🇰🇫🇮 length: 10
xctest[] string: 1⃣➡️▶️♈️🆗🆖🅰🆘✅㊗️ length: 10

UnitTest

https://github.com/matsuokah/NSString-ActualLength/tree/master/NSString%2BActualLengthTests
[追記] リネーム漏れがあり、actualLengthのテストが正常に行われていないのにもかかわらず全て成功するというバグがありました。
@miyakeryo@github さん、ご指摘ありがとうございました。(2015/04/29)

Attention

ただしiOS8.3以降の仕様であるZero-width joinerで複数の絵文字をつなげた場合に1つの絵文字にまとめるは1文字としてカウントせず、つなげられている絵文字の数だけカウントされる。
なぜなら、iOS8.2以前及びAndroidで複数の絵文字が展開されるため。

Hipchatのスクショ

Pasted_Image_4_23_15__12_29_AM.png

18
19
2

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
18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?