Delete all letters from String - kotlin

How can i delete all letters from String?
I've got given String:
val stringData ="ABC123.456"
Output value:
val stringData ="123.456"

We can try regex replacement here:
val regex = """[A-Za-z]+""".toRegex()
val stringData = "ABC123.456"
val output = regex.replace(stringData, "")
println(output) // 123.456

Related

Format number based on pattern

I need to format numbers based on pattern given in the code.
Number : 12038902.9, Pattern : "##,###,###.##". Output must be like : 12,038,902.9 I have to use this "##,###,###.##" & "##.###.###,##" also.
I have tried this but not working :
fun main() {
val number = 12038902.90
val pattern = "##,###,###.##"
val formattedNumber = formatNumber(number, pattern)
println(formattedNumber)
}
fun formatNumber(number: Double, pattern: String): String {
val parts = pattern.split(".")
val integerPart = parts[0].replace(",", "")
val decimalPartFormat = parts[1]
val intPartFormat = "%d"
val decimalPartForm = "%.${decimalPartFormat.length}f"
val formattedIntPart = String.format(intPartFormat, number.toInt()).replaceFirst("(?<=\\d)(?=(\\d{3})+(?!\\d))".toRegex(), ",")
val decimalPart = (number * 10.0.pow(decimalPartFormat.length)).toInt() % 10.0.pow(decimalPartFormat.length).toInt()
val formattedDecimalPart = String.format("%0${decimalPartFormat.length}d", decimalPart).replaceFirst("0*$".toRegex(), "").replaceFirst("(?<=\\d)(?=(\\d{3})+(?!\\d))".toRegex(), ",")
return "$formattedIntPart.$formattedDecimalPart"
}
Getting this output : 12,038902.9 which is wrong I want is 12,038,902.9:
Pattern & number both are dynamic so I need to adjust as per it's need.
maybe u can use DecimalFormat for this purpose. It takes care of grouping, proper separators etc.
Result for your the input 12038902.9 is: 12,038,902.9
fun convert(number: String) {
val decimalFormatSymbols = DecimalFormatSymbols()
decimalFormatSymbols.decimalSeparator = '.'
decimalFormatSymbols.groupingSeparator = ','
val decimalFormat = DecimalFormat()
decimalFormat.decimalFormatSymbols = decimalFormatSymbols
decimalFormat.groupingSize = 3
decimalFormat.maximumFractionDigits = 2
decimalFormat.minimumFractionDigits = 1
decimalFormat.maximumIntegerDigits = 8
decimalFormat.maximumIntegerDigits = 8
val formattedNumber = decimalFormat.format(number.toDoube())
println(formattedNumber)
}
Try with:
val number = 12038902.9
val pattern = "##,###,###.##"
val formattedNumber = DecimalFormat(pattern).format(number)

Remove character or word from string in kotlin

Hey I want to remove character/word or sentence from string.
For example
val string = "Hey 123"
or
val string = "Hey How are you 123"
or
val string = "Hey!! How are you 123"
and output
string = 123
If you only want the digits:
val result = string.filter { it.isDigit() }
Alternatively if you want to omit letters (and maybe also whitespace):
val result = string.filter { !it.isLetter() }
val result = string.filter { !it.isLetter() && !it.isWhitespace() }

how to replace duplicated string using re{n,} in Kotlin?

I want change "aaa" or "aa..." to "." using Regex(re{2,})
Below is my code
var answer = "aaa"
var re = Regex("re{2,}a") // Regex("are{2,}")
answer = re.replace(answer,".")
println(answer)
Regex("re{2,}a") and Regex("are{2,}")
Both println aaa
How can I replace duplicated string using re{n,} ??
fun main(args: Array<String>) {
var tests = arrayOf("a","aa","aaa","aaaa")
val re = Regex("a(a+)")
tests.forEach {t->
val result = re.replace(t,".")
println(result)
}
}
output:
a
.
.
.
Generic regex to replace any duplicates (not only duplicate a symbols) is (?<symbol>.)\k<symbol>+
You may define an extension function for convenient usage:
private val duplicateRegex = "(?<symbol>.)\\k<symbol>+".toRegex()
fun String.replaceDuplicatesWith(replacement: String): String = replace(duplicateRegex, replacement)
Usage:
println("a".replaceDuplicatesWith(".")) //a
println("aaa".replaceDuplicatesWith(".")) //.
println("aa...".replaceDuplicatesWith(".")) //..
If you want duplicates to be iteratively replaced (like "aa..." -> ".." -> ".") you'll need an auxilary recursive method:
tailrec fun String.iterativelyReplaceDuplicatesWith(replacement: String): String {
val result = this.replaceDuplicatesWith(replacement)
return if (result == this) result else result.iterativelyReplaceDuplicatesWith(replacement)
}
Usage:
println("a".iterativelyReplaceDuplicatesWith(".")) //a
println("aaa".iterativelyReplaceDuplicatesWith(".")) //.
println("aa...".iterativelyReplaceDuplicatesWith(".")) //.

How to convert string to char in Kotlin?

fun main(args: Array<String>) {
val StringCharacter = "A"
val CharCharacter = StringCharacter.toChar()
println(CharCharacter)
}
I am unable to convert string A to char.
I know that StringCharacter = 'A' makes it char but I need the conversion.
Thanks.
A CharSequence (e.g. String) can be empty, have a single character, or have more than one character.
If you want a function that "returns the single character, or throws an exception if the char sequence is empty or has more than one character" then you want single:
val string = "A"
val char = string.single()
println(char)
And if you want to call single by a different name you can create your own extension function to do so:
fun CharSequence.toChar() = single()
Usage:
val string = "A"
val char = string.toChar()
println(char)
You cannot convert a String to a Char, because a String is an array of Chars. Instead, select a Char from the String:
val string = "A"
val character = string.get(0) // Or string[0]
println(character)
A String cannot be converted to a Char because String is an array of chars. You can convert a String to an Char array or you can get a character from that String.
Example:
val a = "Hello"
val ch1 = a.toCharArray()[0] // output: H
val ch2 = a[0] // output: H

How to "prepend" a Char to a String in Kotlin

How in Kotlin can I prepend a Char to a String?
e.g.
fun main(args: Array<String>) {
val char = 'H'
val string = "ello World"
val appendingWorks = string + char //but not what I want...
//val prependingFails = char + string //no .plus(str:String) version
val prependingWorkaround1 = char.toString() + string
val prependingWorkaround2 = "" + char + string
val prependingWorkaround3 = String(charArray(char)) + string
}
When trying to call + (e.g. plus) on Char, there is no version that accepts a String on the right, so therefore 'H' + "ello World" doesn't compile
The first workaround might be good enough but it's a regression for me from what works in Java: String test = 'H' + "ello World"; (compiles fine...)
I also don't like the last workaround, at least in the java.lang.String I have a constructor that accepts a single char, or I can use java.lang.Character.toString(char c). Is there an elegant way in Kotlin to do so?
Was this discussed before (adding a plus(str:String) overload to the Char object?)
What about using string templates, like this:
val prepended = "$char$string"
As of kotlin 1.5, there is an extension plus operator function defined on Char, which can be used to concatenate a Char with given String. So you can do
val char = 'H'
val string = "ello World"
// Use the function call syntax
val result1 = char.plus(string)
// or use the operator syntax
val result2 = char + string
If you want to truly prepend a string using just a method call on that string, you can do the following:
val str = "ello World!"
println(str.let { 'H' + it })
This way can be useful if str was instead a large complicated chain of method calls:
val squares = ... // 10x10 array of square numbers
println(squares.joinToString("\n") {
it.joinToString(" ") { "%03d".format(it) }
}.let { "Squares:\n" + it })