Last active
July 11, 2022 12:45
-
-
Save Zeta611/adadc88879b3f7a0ddc2d9a50fb25e17 to your computer and use it in GitHub Desktop.
[String+disjointedHangul] Extends `disjointedHangul` method to `String` #extension #iOS
This file contains hidden or 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
// | |
// String+disjointedHangul.swift | |
// | |
// Created by Jay Lee on 08/03/2019. | |
// Copyright © 2019 Jay Lee <[email protected]> | |
// This work is free. You can redistribute it and/or modify it under the | |
// terms of the Do What The Fuck You Want To Public License, Version 2, | |
// as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. | |
// | |
import Foundation | |
private let chosung = ["ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ","ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"] | |
private let jungsung = ["ㅏ","ㅐ","ㅑ","ㅒ","ㅓ","ㅔ","ㅕ","ㅖ","ㅗ","ㅘ","ㅙ","ㅚ","ㅛ","ㅜ","ㅝ","ㅞ","ㅟ","ㅠ","ㅡ","ㅢ","ㅣ"] | |
private let jonsung = ["","ㄱ","ㄲ","ㄳ","ㄴ","ㄵ","ㄶ","ㄷ","ㄹ","ㄺ","ㄻ","ㄼ","ㄽ","ㄾ","ㄿ","ㅀ","ㅁ","ㅂ","ㅄ","ㅅ","ㅆ","ㅇ","ㅈ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"] | |
extension String { | |
/// The string with Korean alphabet *jamo 자모* disjointed. | |
/// | |
/// If the string contains non-Korean alphabets, | |
/// ``` | |
/// let text = "Hello, 세상!" | |
/// print(text.disjointedHangul) | |
/// // prints "Hello, ㅅㅔㅅㅏㅇ!" | |
/// ``` | |
/// | |
/// 0xAC00 corresponds to 가, and 0xD7A3 corresonds to 힣. | |
/// See [The Unicode Standard, Hangul Syllables](http://www.unicode.org/charts/PDF/UAC00.pdf) | |
/// for more on the unicode range of Korean letters. | |
var disjointedHangul: String { | |
reduce(into: "") { partialResult, character in | |
// Checks if `character` is a Korean alphabet, hangul. If not, continue to the next character. | |
guard let unicode32 = character.unicodeScalars.first?.value, | |
(0xAC00...0xD7A3).contains(unicode32) | |
else { | |
partialResult += String(character) | |
return | |
} | |
let unicode = Int(unicode32 - 0xAC00) | |
let chosungIndex = unicode / 21 / 28 | |
let jungsungIndex = unicode % ( 21 * 28 ) / 28 | |
let jongsungIndex = unicode % 28 | |
partialResult += chosung[chosungIndex] + jungsung[jungsungIndex] + jonsung[jongsungIndex] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment