英文:
Convert substring to int in golang
问题
我有这个变量:
danumber := "542353242"
并且想从字符串中提取一个字符,并将其作为数字进行操作。
尝试了这个:
int(danumber[0])
但似乎不起作用。
英文:
I have this variable:
danumber := "542353242"
and want to extract a character from the string and operate with it as a number.
Tried this:
int(danumber[0])
but it doesn't seem to work.
答案1
得分: 4
你的表达式给出的是数字的字符编码。要将字符转换为字符的值,可以从字符编码中减去字符0
的编码:
int(danumber[0] - '0') // 在你的例子中,这是:53 - 48
如果你想要转换多个数字,我建议使用strconv
包:
number, err := strconv.Atoi(danumber[0:2]) // 将前两个字符转换为整数
英文:
What your expression gives you is the character code for the digit. To convert the character to the character's value, subtract 0
's character code from it:
int(danumber[0] - '0') // in your example, this is: 53 - 48
If you want to convert multiple digits, I would recommend using the strconv
package:
number, err := strconv.Atoi(danumber[0:2]) // convert first two characters to int
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论