25

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.

2
  • You mean convert a character to its code? Commented Nov 11, 2017 at 5:53
  • @JulianSoto yes, mean a= 97 b=98 like that Commented Nov 11, 2017 at 5:55

4 Answers 4

21

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.

Sign up to request clarification or add additional context in comments.

Comments

18

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

4 Comments

finally your solution worked thanks , and I used char.value[0].toInt() does it make any difference with yours?
No, no difference
No. The only difference is the exception thrown if the string is empty. first() will give you NoSuchElementException while get(Int) will give you StringIndexOutOfBoundsException
Exception will never thrown in my case as it is in foreach loop , thanks :)
8

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()
}

3 Comments

The code with problem was missing before,? Now ,I have changed it , check it please, and let me know where i'm mistaking
The code with problem was missing before,? Sorry I didn't understand this sentence, have you missed something between the , and ??
simply check my edited question and please help me to figure it out it is not working with character when fetched with regEx matching
4

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.

1 Comment

In the code example, 'A' is not a String.

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.