Need to replace a String that looks like this “xxxx-xxxx” with a given Long, so input output:
“33” -> “xxxx-xx33”
“884433 -> “xx88-4433”
“0” -> “xxxx-xxx0”
They need to get added from the end.
There’s a few ways to do this, such as adding zeros to the input, then the dashes, but I’m wondering if there’s a Kotlin way to do with replace
?
1
You can achieve this in Kotlin using the replace method combined with a regular expression. Here’s how you can do it:
fun replaceWithLong(input: String, longValue: Long): String {
val longString = longValue.toString().padStart(8, '0') // Convert Long to String and pad with zeros
val pattern = "x{4}-x{4}".toRegex() // Pattern to match "xxxx-xxxx"
return pattern.replaceFirst("xxxx-xxxx") {
longString.substring(0, 4) + "-" + longString.substring(4)
}}
fun main() {
println(replaceWithLong("xxxx-xxxx", 33)) // Output: "xxxx-xx33"
println(replaceWithLong("xxxx-xxxx", 884433)) // Output: "xx88-4433"
println(replaceWithLong("xxxx-xxxx", 0))} // Output: "xxxx-xxx0"
- longValue.toString().padStart(8, ‘0’): This converts the Long value to a String and pads it with leading zeros to ensure it’s always 8 characters long.
- “x{4}-x{4}”.toRegex(): This creates a regular expression that matches the pattern “xxxx-xxxx”.
- replaceFirst with lambda: The replaceFirst method is used to replace the first match of the pattern. The lambda function splits the padded longString into two parts and formats them as “xxxx-xxxx”.
This solution ensures the Long value is added to the string from the end, replacing the appropriate “x” characters.