Reputation: 7139
I need to get the first character of a string, currently what I'm using is:
String firstCharacter = getTitle().substring(0, 1);
where getTitle()
returns a String
that can contain multiple words and also emojis, if the first character is an emoji and I use substring
when I display firstCharacter instead of the emoji I get a question mark because using substring
I cut the emoji characters.
What I want to do is:
if the first word is an emoji retrieve and assign it to firstCharacter
without using substring
;
if the first word is an actual word use the substring
as I'm currently doing;
How can I possibly do it?
Upvotes: 2
Views: 1610
Reputation: 554
Kotlin Multiplatform (KMP) version which supports Emojis, as well as other multibyte strings
// libs used:
implementation("de.cketti.unicode:kotlin-codepoints-deluxe:0.9.0") // For KMP and to support some 4-byte strings afaict
implementation("org.kodein.emoji:emoji-kt:2.1.0")
/**
* Multibyte (e.g. Chinese, emoji) safe way to fetch the first character of a string
*/
fun String.firstCharacter(): String {
if (this.length < 2) return this
EmojiFinder().findEmoji(this).firstOrNull()?.let {
if (it.start == 0) return this.substring(it.start, it.end)
}
return this.take(this.offsetByCodePoints(0, 1))
}
@Test
fun testFirstCharater() {
assertEquals("", "".firstCharacter())
assertEquals("1", "1".firstCharacter())
assertEquals("J", "Johny".firstCharacter())
assertEquals("\uD83D\uDE0A", "\uD83D\uDE0A Regular emoji".firstCharacter())
assertEquals("\uD83C\uDDEB\uD83C\uDDF7", "\uD83C\uDDEB\uD83C\uDDF7 flag".firstCharacter())
assertEquals(
"\uD83E\uDD26\uD83C\uDFFC\u200D♂\uFE0F",
"\uD83E\uDD26\uD83C\uDFFC\u200D♂\uFE0F facepalman".firstCharacter()
)
assertEquals("读", "读写".firstCharacter())
assertEquals("中", "中文".firstCharacter())
assertEquals("ض", "ضط arabic".firstCharacter())
assertEquals("ਆ", "ਆ 3 bytes".firstCharacter())
assertEquals("\uD808\uDC16", "\uD808\uDC16 4 byte char".firstCharacter())
}
Upvotes: 1
Reputation: 644
Just use String.codePointAt()
new String(Character.toChars(getTitle().codePointAt(0)))
Upvotes: 2
Reputation: 5517
EmojiCompat is used to support Emojis in Android. You can initialize it by downloading it or packaging it within your app.
// Initialize with your desired config
EmojiCompat.init(BundledEmojiCompatConfig(context))
// Check if EmojiCompat was successfully loaded
if (EmojiCompat.get().loadState == EmojiCompat.LOAD_STATE_SUCCEEDED) {
EmojiCompat.get().hasEmojiGlyph(yourString)
}
Emojis range can be found here
So, this would result in (not tested):
if(getTitle().substring(0,5)
== ("/[\u2190-\u21FF] | [\u2600-\u26FF] | [\u2700-\u27BF] |
[\u3000-\u303F] | [\u1F300-\u1F64F] | [\u1F680-\u1F6FF]/g")){
firstCharacter = getTitle().substring(0,5);
} else{
firstCharacter = getTitle().substring(0,1);
}
Upvotes: 1