BBK#1: Find Middle Element

problemsolving Nov 16, 2020

Don't be a Java-ish dev in Kotlin-ish world, improve your knowledge about Koltin Standard Library and write better Kotlin code. ✌🏻 If your Java dev migrating to Kotlin this will help you learn alot!

Question: Print middle character of a string, if even print middle two characters else middle character

Try it put yourself :
πŸ‘¨πŸ»β€πŸ’»πŸ‘‰ https://www.codewars.com/kata/56747fd5cb988479af000028/train/kotlin



Solution 1:

fun getMiddle(word : String) : String {
	val chars = word.toCharArray()
	val mid = chars.size/2
	return  if(chars.size%2==0){
		"${chars.get(mid-1)}${chars.get(mid)}"
	}else{
		"${chars.get(mid)}"
	}
}

Solution 2:

Using drop
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/drop.html

fun getMiddle(word : String) : String {
	val worldLength = (word.length - 1) / 2
	return word.drop(worldLength).dropLast(worldLength)
}

Solution 3:

Using substring + ranges
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/substring.html

fun getMiddle(word: String): String = word
		.substring((word.length-1)/2 .. word.length/2)


Conclusion

Aim of these articles is not hate on Java, but to help people learn various ways in which they can write same logic better and more Kotlin standard library focused way.

Hope you find it informative and if you have any feedback or post request or want to subscribe to my mailing list forms are below.

Until next time. Happy Hacking! πŸ‘©β€πŸ’»

Solve Next :

BigBrainKotlin - Find Max Min
Don’t be a Java-ish dev in Kotlin-ish world, improve your knowledge about Koltin Standard Library and write better Kotlin code. ✌🏻 If your Java dev migrating to Kotlin this will help you learn a lot!

Enjoy the Post?

a clap is much appreciated if you enjoyed. No sign up or cost associated :)




Chetan gupta

Hi there! call me Ch8n, I'm a mobile technology enthusiast! love Android #kotlinAlltheWay, CodingMantra: #cleanCoder #TDD #SOLID #designpatterns

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.