Reputation: 39
For a numbered string (1234
) I normally use the package strconv
with the function Atoi
to convert from string to int in Go. However, what is the idiomatic way of approaching this if the numbered string starts with leading zeros (e.g. 01234
)?
Slicing the string and then converting the []string
to []int
, is one approach, but is it the best/idiomatic way Go-ing about it?
Update 1:
From input string 01234
, expected output 01234
as any type int (in any kind of simple or composed type of int, e.g. foo := "01234"
to bar = []int{0, 1, 2, 3, 4}
).
Is there an idiomatic (or standard package func) to approach this problem, or is the string to rune/byte conversation (do some business logic and then convert back) necessary when the variable has one or more leading zeros (e.g. 01234
or 00001
).
Update 2: Just to make it completely clear, as I can feel the question can be clarified future: foo, _ := strconv.Atoi("01234")
returns 1234
as an int
(and same result can be obtained in other ways with strings
package etc.).
The question here is, how (if possible, in Go idiomatic) can I get the result with the leading zeros, that is, 01234
(and NOT 1234
) in type int
?
Upvotes: 3
Views: 5515
Reputation: 396
fmt.Printf("%01d ", 5) // 5
fmt.Printf("%02d ", 5) // 05
fmt.Printf("%03d ", 5) // 005
fmt.Printf("%04d ", 5) // 0005
myInt := fmt.Sprintf("%05d ", 5)
fmt.Println(myInt) // 00005
https://pkg.go.dev/fmt#pkg-overview
Upvotes: 2
Reputation: 11
To convert a string of decimals to a slice of integers for those decimal values, loop over the string and convert the rune to the corresponding integer using subtraction:
func toIntSlice(s string) ([]int, error) {
var result []int
for _, r := range s {
if r < '0' || r > '9' {
return nil, fmt.Errorf("not an integer %s", s)
}
result = append(result, int(r-'0'))
}
return result, nil
}
Example use:
foo := "01234"
bar, _ := toIntSlice(foo)
// bar is []int{0, 1, 2, 3, 4}
https://go.dev/play/p/etHtApYoWUi
Upvotes: 0
Reputation: 778
use strings.TrimLeft(s, "0")
to remove leading zeroes from the string.
Upvotes: 2