Home > front end >  Is there any way duplicated sequential string delete in kotlin
Is there any way duplicated sequential string delete in kotlin

Time:12-02

I got strings like

String1=277473—-2627272———-273-3838383-/./--asdfg-----123:12:2---

I cant take length of function because I have multiple strings with different lenghts.

I wanted to use split function to take them as a variable but I need this format

String1=277473-2627272—273-3838383-/./-asdfg-123:12:2

Is there any way to do that easily?

CodePudding user response:

You are using 2 different kind of '-' characters, use this instead:

fun formatString(string: String): String {
   return string.mapNotNull { char -> if (char == '—' || char == '-') '-' else char }
        .joinToString(separator = "")
        .replace("""- """.toRegex(), "-")
        .trimDashes()
}

fun String.trimDashes(): String = dropWhile { it == '-' }
    .dropLastWhile { !it.isDigit() }

CodePudding user response:

you can do something like this:

fun formatString(string: String): String {
   return string.trimDashes()
        .split("-")
        .joinToString(separator = "-", transform = String::trimDashes)
}

fun String.trimDashes(): String = dropWhile { it == '-' }
    .dropLastWhile { !it.isDigit() }
  • Related