如何将Char转换为Int? [英] How do I convert a Char to Int?

查看:99
本文介绍了如何将Char转换为Int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个String整数,看起来像"82389235",但是我想遍历它,将每个数字分别加到MutableList上.但是,当我按照自己认为的方式进行处理时:

So I have a String of integers that looks like "82389235", but I wanted to iterate through it to add each number individually to a MutableList. However, when I go about it the way I think it would be handled:

var text = "82389235"

for (num in text) numbers.add(num.toInt())

这会将与字符串完全无关的数字添加到列表中.但是,如果我使用println将其输出到控制台,它会很好地遍历字符串.

This adds numbers completely unrelated to the string to the list. Yet, if I use println to output it to the console it iterates through the string perfectly fine.

如何正确地将Char转换为Int?

推荐答案

这是因为numChar,即结果值是该char的ascii值.

That's because num is a Char, i.e. the resulting values are the ascii value of that char.

这可以解决问题:

val txt = "82389235"
val numbers = txt.map { it.toString().toInt() }

map可以进一步简化:

map(Character::getNumericValue)

这篇关于如何将Char转换为Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆