How to convert char to ascii value in kotlin language - android

I am developing an android application with kotlin in which I need to convert an string character to its ASCII value,
fun tryDiCript(cypher: String) :String {
var cypher = "fs2543i435u#$#g###sagb#!#12416###"
var originalText = ""
var regEx =Regex("[a-z]")
for(char in regEx.findAll(cypher))
{
originalText += (char.value.toInt()).toString()
}
return originalText
}
this tutorial website showed me to use char.toInt() but it gives runtime error saying
Caused by: java.lang.NumberFormatException: Invalid int: "u"
so how if anyone knows hot to convert char to ASCII value please help me.

char.value is a String. When you call String.toInt(), it is expecting a numeric string such as "1", "-123" to be parsed to Int. So, "f".toInt() will give you NumberFormatException since "f" isn't a numeric string.
If you are sure about char.value is a String containing exactly one character only. To get the ascii value of it, you can use:
char.value.first().code

Since Kotlin 1.5
if your variable is of type char for example 'a' you can simply use a.code.
The old methods (e.g. toByte()) are deprecated now.

You said ascii, not unicode. So it's easy.
This is an example that shows you how to convert a char ('A') to it's ascii value.
fun main(vararg args: String) {
println('A'.toByte().toInt())
}
The output is what we expected, 65.
Note this doesn't work with unicode.
Edit 1
I guess this to work.
fun tryDiCript(cypher: String): String {
var cypher = "fs2543i435u#$#g###sagb#!#12416###"
var originalText = ""
var regEx = Regex("[a-z]")
for(char in regEx.findAll(cypher))
originalText += char.value[0].toInt().toString()
return originalText
}
And I recommend you to use StringBuilder.
fun tryDiCript(cypher: String): String {
var cypher = "fs2543i435u#$#g###sagb#!#12416###"
val originalText = StringBuilder()
var regEx = Regex("[a-z]")
for(char in regEx.findAll(cypher))
originalText.append(char.value[0].toInt())
return originalText.toString()
}

I checked #ice1000's answer, I found the block below does not work.
fun main(vararg args: String) {
println('A'.toByte().toInt())
}
As we can see in the Kotlin Documentation String - Kotlin Programming Language,the toByte() function of String "Parses the string as a signed Byte number and returns the result." If the the content of the string is not a number, it will throw a java.lang.NumberFormatException.
But there is another function of String called toByteArray(),this function does no require the content of the string being numbers. My code is as following:
String tempString = "Hello"
val tempArray = tempString.toByteArray()
for (i in tempArray){
println(i.toInt())
}
Attention that toByteArray() function's definition in kotlin's documentaion:
fun String.toByteArray(
charset: Charset = Charsets.UTF_8
): ByteArray
The default charset is UTF-8, if you would like to use other charset, you can modify it with the parameter.

Related

How to check string has digit only in kotlin

I'm working in Kotlin Android.
The string is coming from the server, and it might contain digit, character, empty string or null value. I want to convert that value into double because I want to compare values.
So is there any better way to check that string contains only digit value and not empty or null in a Kotlin way. The list is huge, so I want an efficient way.
Price.kt
data class Price(
var value: String? = null
)
main.kt
val defaultValue : Double = 4.23
val list = listOf(Price("2.33"), Price("fr23"), Price(""), Price(null), Price("4.23"), Price("12.23"))
list.forEach{
if(it == defaultValue){
println("Found It")
}
}
Kotlin already has an efficient solution: toDoubleOrNull
Parses the string as a Double number and returns the result or null if
the string is not a valid representation of a number.
if (list.any { it.value.toDobleOrNull() == defaultValue }) {
println("Found It")
}

Multi type object in kotlin

from an API call i get as response a body with this structure
open class BaseResponseEntity {
#SerializedName("result")
val result: ResultEnum = ResultEnum.NONE
#SerializedName("errorCode")
val errorCode: String = ""
#SerializedName("errorMessage")
val errorMessage: String = ""
#SerializedName("successMessage")
val successMessage: String = ""
#SerializedName("value")
val code: LastPaymentCodeModel?
}
where the field "value" can be three types: null, String or LastPaymentCodeModel. How can i get this?
I managed to put a ? so that both null and LastPaymentCodeModel are handled, but i don't know how to handle the String type too.
I think the best approach would probably be to use type Any? for code.
Then you should write a custom GSon serializer/deserilizer (JsonDeserializer<BaseResponseEntity>) for the BaseResponseEntity object.
In this Json deserializer, you would need to check the type of value (e.g is it a string or a data structure) and decode it to the correct object type.
Alternative, to avoid the use of Any?, you could leave the model exactly as you have it. You will still need to write a custom JsonDeserializer, however if value is a string then it would still create a LastPaymentCodeModel, using the string value as one of it's properties.

kotlin double with 4 number after comma in Android

The default of Double in android kotlin is 1121.57. How to convert it to 1.121,5767 to make 4 number after comma? even though behind the comma is 0 like this: 1.121,0000
You could write an extension function for Double and use a German format for the output, like this:
fun main() {
val myDouble: Double = 1121.57
val anotherDouble: Double = 100000.99
println(myDouble.format(4))
println(anotherDouble.format(4))
}
fun Double.format(digits:Int) = String.Companion.format(
java.util.Locale.GERMAN,
"%#,.${digits}f",
this
)
It returns the following String
1.121,5700
100.000,9900
please pass your value to the following function and let me know if it works for you.
fun formattedNumber(number: Double): String{
val formattedNumber = String.format("%.7f", number)
val split = formattedNumber.split(".");
val str = StringBuilder(split[1])
str.insert(3, ',')
return "${split[0]}.${str}"
}
Take a look at the BigDecimal class. You can easily set the scale to 4 digits and it can be created with a Double.

Kotlin pass string with escaped Dollar sign

In our project I want to pass string with dollar sign. Final result should look like this: ~ $1300. But I get only ~ the rest is not print. By debugging I found out that the issue is the dollar sign. How I can pass strings with dollar sign? Escaping dollar sign not solving this problem.
fun setItem() {
bind(valueSubtitle = "~ \$${trx.currencyAmount}")
}
fun bind(valueSubtitle: String? = null) {
val valueSubtitleTextView = findViewById(R.id.txtValueSubtitle)
valueSubtitleTextView.text = valueSubtitle
}
I don't have issues with direct printing string with dollar sign. I have issue when I try to pass this string to other function, and only then print it.
Update
I debugged, and found out that I have issue when my number has double zero at the end: 189.00 or 123.00. These number causes the problem. Other number like 123.40 or 1152.90 shows correctly.
Update 2
Issue was with my TextView. It behaved strangely when it was printing different double numbers. It was solved when I changed android:layout_width="match_parent" to android:layout_width="wrap_content"
You could try for a literal representation.
fun main(args: Array<String>) {
val amount = "25"
val escapedString = "~ ${'$'}$amount"
printString(escapedString)
}
fun printString( str : String) {
println(str)
}
Templates are supported both inside raw strings and inside escaped strings. If you need to represent a literal $ character in a raw string (which doesn't support backslash escaping), you can use the following syntax:
itemAmount.bind(valueSubtitle = "~ \${'$'}${trx.currencyAmount}")
Looks pretty bad syntax, but will work.
Try this
class MainActivity : AppCompatActivity() {
private val trx: Transaction = Transaction(1300.00)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setItem()
}
fun setItem() {
bind(valueSubtitle = "~ \$${trx.currencyAmount}")
}
fun bind(valueSubtitle: String? = null) {
val valueSubtitleTextView: TextView = findViewById(R.id.textview)
valueSubtitleTextView.text = valueSubtitle
}
class Transaction(var currencyAmount: Double)
}
There is nothing wrong with the code you have shown. Note also that you can use several ways to escape the dollar sign and that in your specific case you wouldn't even need to escape it. Just compare with the following sample code:
data class Container(val amount : Double = 123.00)
fun main() { // used Kotlin 1.3
val trx = Container()
listOf("~ \$${trx.amount}", // your variant
"~ $${trx.amount}", // easier and works too
"""~ $${trx.amount}""", // everything in this string must not be escaped
"~ ${'$'}${trx.amount}", // actually you may only use this if you require something like shown below (e.g. if you want to print something like $none)
"""~ ${"$"}${trx.amount}""", // similar to the one before
// variants to print $none:
"~ \$none",
"~ ${'$'}none",
"""~ ${'$'}none""",
"""~ $${""}none"""
)
.forEach(::println)
}
The output of the above is:
~ $123.0
~ $123.0
~ $123.0
~ $123.0
~ $123.0
~ $none
~ $none
~ $none
~ $none
But none of these answers were the solution to your problem. As the $ in your code wasn't the problem as you found out yourself...
This should work.
fun main(args: Array<String>) {
val dollar = "~$"
val amount = 1212
println("${dollar}${amount}")
}

How to apply RegEx to whole string?

Is regular expression matching every single string?
For example:
String s = "android4you2 and 4us";
What's the RegEx that I have to write to make "s" only for [a-z]?
Your question is unclear, to match the whole string, you could do:
if (s.matches("[a-zA-Z0-9 ]+")) { ...
If you want to only test for alphabetic characters:
if (s.matches("[a-zA-Z]+")) { ...
try using this.
String regex = "^[A-Za-z\\s]+$";

Categories

Resources