Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map String with Emojis to Array<String|Char>

I want to convert my String to Array or List of Strings or Chars like: Array<String> or Array<Char>.

Example:

val myText = "Ab😟+🀹2πŸ‘¨πŸ»#βœ…'πŸ‘¨ΓΌπŸ‘¨πŸΏ{" // Parse and print to Log

Should:

[ "A", "b", "😟", "+", "🀹", "2", "πŸ‘¨πŸ»", "#", "βœ…", "'", "πŸ‘¨", "ΓΌ", "πŸ‘¨πŸΏ", "{" ] // Array contains Strings or Chars

Java/ Kotlin method what doesn't work because of Emojis on Android:

myText.toList() // ❌ Fails because of Emojis
myText.toMutableList() // ❌ Fails because of Emojis
like image 464
A. Amini Avatar asked Jul 23 '26 03:07

A. Amini


1 Answers

In Kotlin, if targeting JDK 8 or later you can use:

fun String.splitToCodePoints(): List<String> {
    return codePoints()
        .toList()
        .map { String(Character.toChars(it)) }
}

If using JDK 7, it's more manual:

fun String.splitToCodePoints(): List<String> {
    val list = mutableListOf<String>()
    var count = 0
    while (count < length) {
        with (codePointAt(count)){
            list.add(String(Character.toChars(this)))
            count += Character.charCount(this)
        }
    }
    return list
}

It seems the Kotlin standard library is lacking in these areas since you have to rely on JDK boxed primitive classes to convert the code points integers to Strings.

As mentioned in another answer here, this will have to be more involved if you need to handle the zero width joiner. You might need to remove any zero width joiners so the characters can be shown separately, or you might want to display them together and so need to manipulate the list to combine elements separated by joiners. If the language uses ligatures, this would affect this decision.

like image 54
Tenfour04 Avatar answered Jul 24 '26 17:07

Tenfour04



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!