Library contents

Kotlin replace

Replace every literal hyphen in a warehouse code with a slash.

A simple example

replace

  1. Start with "a-b"
  2. Do this Replace the hyphen with a space
  3. Result "a b"
The surrounding letters keep their positions relative to one another.
Lesson.kt
fun main() {
    val value = "a-b"
    println(value.replace("-", " "))
}
Output
a b

Syntax

Kotlin syntax
label.replace("-", "/")
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Print a shelf code with readable separators

A printed code uses separators or spacing that are awkward for a reader. Convert the display copy to the desired format and preserve the original value needed by the source system.

From the programval label = "A-12-B"
ResultA/12/B
Lesson.kt

fun main() {
    val label = "A-12-B"
    println(label.replace("-", "/"))
}
Output
A/12/B

Both separators change and the order of the individual code fields stays the same.

Advertisements

Display a course slug

A course directory stores a short slug for linking between pages. Derive its display spelling when showing the course so readers see the intended label while the stored slug remains usable.

From the programval value = "data-science"
Resultdata science
Lesson.kt
fun main() {
    val value = "data-science"
    println(value.replace("-", " "))
}
Output
data science

The two words are separated for display.

Display a route slug

A directory stores a public name as a short slug. Turn the stored spelling into the display form required by the interface while keeping the identifier used for lookup available separately.

From the programval value = "north-gate-two"
Resultnorth gate two
Lesson.kt
fun main() {
    val value = "north-gate-two"
    println(value.replace("-", " "))
}
Output
north gate two

Each literal hyphen is replaced.

What to watch for

A literal replacement and a regular-expression replacement treat punctuation differently.

Documentation for replace