swiftで濁点のついた文字列の扱いについて(NFD, NFC)
Swift(3.1基準)で特殊文字の入った文字列を扱う場合、濁点や半濁点が他の文字と合体(?)して非常に分かりづらい状況になる事がある。
☆.・。+:゚*。・
上の文字列の中で赤い部分の様に"半濁点"が左の文字と合体(NFC状態)してしまって一つの文字として扱われてしまい、replacingOccurrences見たいな普通の文字検索や置換では扱えない場合がある。
こういった場合は文字列を"Unicode Scalar"単位で割って扱う必要がある。
詳細は下を参考しよう。
References
- http://gootara.org/library/2016/10/sssjf.html
- https://ko.wikipedia.org/wiki/유니코드_정규화
- https://another.rocomotion.jp/14368685864590.html
☆.・。+:゚*。・
上の文字列の中で赤い部分の様に"半濁点"が左の文字と合体(NFC状態)してしまって一つの文字として扱われてしまい、replacingOccurrences見たいな普通の文字検索や置換では扱えない場合がある。
こういった場合は文字列を"Unicode Scalar"単位で割って扱う必要がある。
詳細は下を参考しよう。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let comment = "☆.・。+:゚*。・" | |
// 1: Replace using "replacingOccurrences" | |
let escapedCommentOne = comment.replacingOccurrences(of: "\\", with: "\\\\\\\\") | |
.replacingOccurrences(of: "'", with: "'\\\\\\\''") | |
.replacingOccurrences(of: ":", with: "\\\\\\:") | |
// 2: Replace using "String.unicodeScalars.map" | |
let escapedCommentTwo = comment.unicodeScalars.map { scalar in | |
switch scalar { | |
case "\\": | |
return "\\\\\\\\" | |
case "'": | |
return "'\\\\\\\''" | |
case ":": | |
return "\\\\\\:" | |
default: | |
return String(scalar) | |
} | |
}.joined() | |
print("escapedCommentOne: \(escapedCommentOne)\nescapedCommentTwo: \(escapedCommentTwo)") | |
/* | |
Output: | |
escapedCommentOne: ☆.・。+:゚*。・ | |
escapedCommentTwo: ☆.・。+\\\:゚*。・ | |
*/ |
References
- http://gootara.org/library/2016/10/sssjf.html
- https://ko.wikipedia.org/wiki/유니코드_정규화
- https://another.rocomotion.jp/14368685864590.html
댓글
댓글 쓰기