Convert substring to int in golang

huangapple go评论73阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年1月23日 01:56:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/34953063.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定