skip to Main Content

The main thing I’m struggling to check is spaces between characters. I wanted to change a
" " into "_" but only when there is another letter after it… I can’t manage to do it. my current check is:

for (c in userName) {
    if ("$c" == " ") { //How do I check in here if after c comes another word??
       userName = userName.replace("$c", "_")
     }
    }

2

Answers


  1. What about something like this:

        for (index in userName.indices) {
            val letter = userName[index]
            val nextLetter = userName.getOrNull(index + 1)
            // if nextLetter == null it means end of the userName
            if (nextLetter == null || nextLetter != ' ') {
                // Do the replacement
            }
        }
    
    Login or Signup to reply.
  2. This is easier using the APIs provided in Kotlin

    I left some comments to clarify each individual step.
    Generally, manual manipulation of strings will be more difficult than the provided APIs

    Realistically, usage of RegEx would be your best friend, but I wanted to keep this code related rather than solving it in that manner.

    Also, in Kotlin, there is a distinct difference between double quotes " and single quotes '
    Double quotes are a string, and Single quotes are a Char. There is a different API under the 2.

    I use the single quote in string iterator methods to keep it more simple and efficient, rather than having to create new strings each time

    val myUsername = "super dude 25"
    val expectedUsername = "super_dude_25"
    
    val lotsOfSpaces = "  super    dude   58    "
    val expectedSpaces = "super_dude_58"
    
    fun formatUsername(string: String): String {
        // Set var to detect duplicate chars
        var prevChar = ' '
    
        return string.trim() // Remove surrounding spaces to simplify
            .replace(' ', '_') // Spaces into underscores
            .filter { char -> // Remove duplicated underscores
                if (char == '_' && prevChar == '_') false
                else {
                   prevChar = char
                   true 
                }
            }
    }
    
    val updated = formatUsername(myUsername)
    println(updated) // super_dude_25
    assert(updated == expectedUsername)
    
    val second = formatUsername(lotsOfSpaces)
    println(second)
    assert(second == expectedSpaces)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search