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

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%position==0){
                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.



from Recent Questions - Stack Overflow https://ift.tt/2Wk7uVM
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation