Wanna get the first character of the first two wor...
# announcements
r
Wanna get the first character of the first two words from the string, below is my code snippet can any one help to optimize it?
Copy code
val lbl = {txt:String -> txt.toCharArray()[0].toString()}

val username = "Rajendra prasad guru" 
val initials = username.split(" ").let {
    val l = lbl(it[0])
    if(it.size>1) "$l${lbl(it[1])}" else l
}.toUpperCase()
println(initials)

Output is :RP
d
If you really want to optimize here, drop the functional programming style and use
indexOf
.
r
i'm about to use these in the multiple places, so wrote this
lbl
lambda expression in util. functional programming won't help us to do this optimized way so? @Dominaezzz
c
lbl can be written as
txt.first().toString()
๐Ÿ‘ 1
and your whole method could be
Copy code
.splitToSequence(" ").map{it.first()}.take(2).joinToString("")
๐Ÿ‘ 1
d
Might be slightly cheaper to put a limit on that split.
๐Ÿ‘ 1
c
ah true. but a sequence is lazy anyway
d
Laziness helps a bit but there's a difference between returning (the first two words and the rest of the string) and (the first word and the rest of the string)
Hmm, what if the string starts with a space.
Nvm, it's configurable.
c
hmm Iโ€™m not sure I undestand what you mean. from my understanding of sequences it does not matter much where the take(2) is
the splitting is lazy and will stop when the sequence stops
r
@Dominaezzz @christophsturm Thank you both for suggesting me
d
I'm saying use a limit of 1 instead of 2. Then you save having to pull out the second word from the rest of the string.
๐Ÿ‘ 1
c
it does not work with limit 1
but limit = 2 is a good idea
๐Ÿ‘ 1
๐Ÿ‘๐Ÿผ 1
n
how about
"Rajendra prasad guru".split(" ", limit=2).joinToString("") { it.take(1).toUpperCase() }
๐Ÿ‘ 1