Reputation: 582
I have very large(potentially endless) stream of integers similar to input below.
I intend to randomly access this slice and read from string one character at a time, and would like to access the integer represented by the character.
For the code below I was expecting intVal to be an integer value of 3. number[1] gives me the ASCII code for 3 which is 51.
input := "2345892345234502349502345234534234572304520345902384523045"
intVal,_ := strconv.Atoi(input[1])
Essentially, What is the proper way of reading integers from strings in Go ?
Upvotes: 0
Views: 1803
Reputation: 120941
Use the following code to get the numeric value of the decimal number at input[i]
:
b := input[i]
if b < '0' || b > '9' {
// not a decimal number
... handle error here
}
n := int(b) - '0'
Upvotes: 1
Reputation: 51567
You can read one rune at a time and convert to string:
for _,r:=range input {
str:=string(r)
}
Or access randomly:
str:=input[n:n+1]
Upvotes: 0