Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Word from String List in Kotlin

Tags:

android

kotlin

I have a mutable list of strings and I'm trying to remove a word from each of them. The problem is that I don't believe the word is being removed from each line.

    for (item in stringLines) {

        when {

            item.contains("SUMMARY") -> eventLines.add(item)
            item.contains("DTSTART") -> startDateLines.add(item)
            item.contains("DTEND") -> endDateLines.add(item)
            //item.contains("URL:") -> locationLines.add(item)
            //item.contains("CATEGORIES") -> categoriesLines.add(item)
    }

    }

    for (item in eventLines) {

        when{
            item.contains("SUMMARY") -> item.removePrefix("SUMMARY")
        }

    }

The string is

SUMMARY WINTER FORMAL

and I need

WINTER FORMAL

but whatever reason it just doesn't appear. I know how to do this in java but I have no idea how to do this in Kotlin and I could not find any function that was able to accomplish this. What am I missing?

like image 219
Genevieve Avatar asked Mar 04 '23 05:03

Genevieve


2 Answers

removePrefix removes the specific part of the string only if that is the prefix. Obviously, this is not your case. You could do a split, filter, join sequence to yield your expected result.

println("SUMMARY WINTER FORMAL".split(" ").filter { it != "SUMMARY" }.joinToString(" ")) 
//output : "WINTER FORMAL"

But if you have multiple contiguous spaces, they will become one space in the output. Also this method does not work if "SUMMARY" is not surrounded by spaces, e.g. "SUMMARYWINTERFORMAL" won't be changed.

You can remove part of the string by replacing it with empty string, but note that this will keep any surrounding characters including the surrounding spaces.

println("SUMMARY WINTER FORMAL".replace("SUMMARY",""))
//output : " WINTER FORMAL"

Note that there is a space in front of "WINTER"

If you wan't to include the spaces if any, using Regular Expression would do:

println("SUMMARY WINTER FORMAL".replace("\\s*SUMMARY\\s*".toRegex(),""))
//output : "WINTER FORMAL"
println("SUMMARYWINTERFORMAL".replace("\\s*SUMMARY\\s*".toRegex(),""))
//output : "WINTERFORMAL"
println("  SUMMARY  WINTER FORMAL".replace("\\s*SUMMARY\\s*".toRegex(),""))
//output : "WINTER FORMAL"

You can modify the regular expression even more to better suit your use case.

like image 72
Ricky Mo Avatar answered Mar 15 '23 22:03

Ricky Mo


Strings in Kotlin (and Java) are immutable. So item.removePrefix returns a new String and you have to update the list or create a new list like this:

for (item in eventLines) {

    when {
        item.contains("SUMMARY") -> 
            eventLinesWithPrefixRemoved.add(item.removePrefix("SUMMARY"))
        else -> eventLinesWithPrefixRemoved.add(item)
    }

}
like image 34
Alexander Egger Avatar answered Mar 15 '23 23:03

Alexander Egger