How to replace any character in any position according to the pattern

Issue

I have a problem like the below:

Given a string and a character and position need replace, for example as below:

Input: string: str ABCDEFGH, prefix “_” and position 3, Output: result AB_CDE_FGH

Input: string: str 10000000, prefix “_” and position 3, Output: result 10_000_000

Input: string: str 10000000, prefix “_” and position 2, Output: result 10_00_00_00

This is my code:

fun convertNumberByCharacter(pattern:String,position: Int,characters: String):String{
    val strBuilder  StringBuilder()
    val arr  pattern.toCharArray()
    return if (arr.size>position){
        for (i in 0..arr.size-1){
            if (i%position0){
                strBuilder.append(characters)
            }
            strBuilder.append(arr[i])
        }
        strBuilder.toString()

    }else{
        pattern
    }
}

Note: DecimalFormat and NumberFormat cannot be used in this problem.

Please, Anyone could help me. Thank you.

Solution

Try this

val str  "ABCD"
val prefix  "_"
val position  3
val result  StringBuilder()

val offset  position - str.length % position
for (i in str.indices) {
    if (i ! 0 && (i + offset) % position  0) {
        result.append(prefix)
    }
    result.append(str[i])
}
println(result)

I think reverse string then loop, add prefix at a position then reverse again also solve this problem

Answered By – Linh

Leave a Comment