0

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.

1
  • 1
    Hi there, here are some hints that might help you find an answer. It's important to start counting from the end of the string (your current loop starts at the left). To go 'backwards', you could reverse your string. As String is an Iterable you can chunk it into position sizes, and then 'insert' your separator using joinToString on the chunked list.
    – aSemy
    Sep 22, 2021 at 9:49

3 Answers 3

2

Here's an implementation using standard Kotlin library functions - no need for mucking around with indices.

fun main() {
    println(convert("ABCDEFGH", 3, "_")) // AB_CDE_FGH
    println(convert("10000000", 3, "_")) // 10_000_000
    println(convert("10000000", 2, "_")) // 10_00_00_00
}

fun convert(input: String, position: Int, separator: String) =
  input
    // reverse the string
    // e.g. HGFEDCBA
    .reversed()
    // split into chunks 
    // e.g. [HGF], [EDC], [BA]
    .chunked(position) 
    // join the chunks back into a string, with a separator 
    // e.g. HGF_EDC_BA
    .joinToString(separator)
    // un-reverse the string - done!
    // e.g. AB_CDE_FGH
    .reversed()

It's important to start counting from the end of the string (your current loop starts at the left). To go 'backwards' I've reversed the input string. As String is an Iterable I've used chunk to split it into position sizes, and then 'inserted' the separator using joinToString on the chunked list. Finally I call reverse again to undo the initial reversal.

4
  • 1
    This's a beautiful answer, but I'm not found "reversed()" in String with Kotlin, So Can you tell me which version of Kotlin you are using? Thank you a lot.
    – Thang
    Sep 29, 2021 at 9:52
  • Thanks! From what I can see in the docs reversed() has been in since 1.0, and for all platforms since 1.3. Here's the source code. I'm using 1.5 Kotlin/JVM. What version do you have?
    – aSemy
    Sep 29, 2021 at 10:21
  • I'm so sorry because my mistake, Thank you again.
    – Thang
    Sep 30, 2021 at 4:41
  • No need to apologise! If you had a problem please explain what it was and how you resolved it, in case someone else has the same issue and you could help them.
    – aSemy
    Sep 30, 2021 at 9:17
1

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

1
  • Can you tell me the reason why you can calculate offset?
    – Thang
    Sep 22, 2021 at 11:10
0

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.

2
  • It feels like chunkedRight() should be really more concise, but this first chunk makes it hard to use map() or similar utils and keep the good performance (so no list copying and no conditionals for each chunk). I'm open to suggestions for improvements.
    – broot
    Sep 22, 2021 at 12:12
  • Yep, After I'm put a question, I'm received so many answers about "chunked" and "joinToString" and I'm seeing some answers very beautifully, including your answer, Thank you.
    – Thang
    Sep 30, 2021 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.