Skip to content

Instantly share code, notes, and snippets.

@Zeta611
Last active July 11, 2022 12:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zeta611/adadc88879b3f7a0ddc2d9a50fb25e17 to your computer and use it in GitHub Desktop.
Save Zeta611/adadc88879b3f7a0ddc2d9a50fb25e17 to your computer and use it in GitHub Desktop.
[String+disjointedHangul] Extends `disjointedHangul` method to `String` #extension #iOS
//
// String+disjointedHangul.swift
//
// Created by Jay Lee on 08/03/2019.
// Copyright © 2019 Jay Lee <jaeho.lee@snu.ac.kr>
// 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