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%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.
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.