Home > other >  How to replace any character in any position according to the pattern
How to replace any character in any position according to the pattern

Time:09-22

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.

CodePudding user response:

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

CodePudding user response:

I think the cleanest way to accomplish this would be to use a combination of chunked() and joinToString(). Unfortunately, stdlib only provides chunked() that counts from the left and we need to count from the right here. Still, I think it is cleaner to implement chunkedRight() and use it with joinToString().

fun CharSequence.chunkedRight(size: Int): List<String> {
    if (isEmpty()) return emptyList()

    val fullChunks = length / size
    val firstSize = length - fullChunks * size

    // capacity may be too big by one - no problem here
    return ArrayList<String>(fullChunks   1).apply {
        if (firstSize > 0) {
            add(substring(0, firstSize))
        }

        (firstSize until length step size).forEach {
            add(substring(it, it   size))
        }
    }
}

Or alternatively:

fun CharSequence.chunkedRightSequence(size: Int): Sequence<String> {
    if (isEmpty()) return emptySequence()

    val firstSize = (length - 1) % size   1
    return sequenceOf(substring(0, firstSize))  
            (firstSize until length step size).asSequence()
                .map { substring(it, it   size) }
}

Then we can use it like this:

println("ABCDEFGH".chunkedRight(3).joinToString("_"))
println("10000000".chunkedRight(3).joinToString("_"))
println("10000000".chunkedRight(2).joinToString("_"))

Or we can create a specialized function for this.

  • Related