Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split character from string in Idiomatic way Kotlin

Hey I am working in kotlin. I have one string in which I want to split into list from there where I should provide character. I’ll explain in details

For example 1

val string = "Birth Control"

val searchText = "n"

Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["Birth Co", "trol"]

For example 2

val string = "Bladder Infection"
    
val searchText = "i"

Actual Output

["Bladder ", "nfect", "on"]

Expect Output

["Bladder ", "nfection"]

I tried some code but example 1 is working fine but example 2 is not because I only want to split first occurrence.

val splitList = title?.split(searchText, ignoreCase = true)?.toMutableList()
splitList?.remove(searchText)

Can someone guide me how to solve this idiomatic way. Thanks

>Solution :

You miss the limit option of the split function. If you give it a value of 2 the result list will have a maximum of 2 entries:

val result = "Bladder Infection".split("i", ignoreCase = true, limit = 2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading