I want to convert string to integer in golang.
As you've already mentioned, there is a strconv.ParseInt
function that does exactly this!
But I don't know the format of string.
That sounds scary (and challenging), but after looking at your examples I can easily conclude you know the format and the problem can be stated like this:
How can I parse an initial portion of a string as an integer?
As strconv.ParseInt
returns 0 on syntax error it's not a good fit; well, at least not a good fit directly. But it can parse your initial portion if you extract it. I'm sure you've already figured it out, but this is really the cleanest solution: extract your content from the string, parse it.
You can extract the leading integer in a few ways, one of them is by using regexp
:
package main
import (
"fmt"
"regexp"
"strconv"
)
// Extract what you need
var leadingInt = regexp.MustCompile(`^[-+]?\d+`)
func ParseLeadingInt(s string) (int64, error) {
s = leadingInt.FindString(s)
if s == "" { // add this if you don't want error on "xx" etc
return 0, nil
}
return strconv.ParseInt(s, 10, 64)
}
func main() {
for _, s := range []string{"10", "65.0", "xx", "11xx", "xx11"} {
i, err := ParseLeadingInt(s)
fmt.Printf("%s\t%d\t%v\n", s, i, err)
}
}
http://play.golang.org/p/d7sS5_WpLj
I believe this code is simple and clearly demonstrates the intentions. You're also using standard ParseInt
which works and gives you all the error checking you need.
If for any reason you can't afford extracting the leading integer (you need it blazing fast parsing terabytes of data and your boss is screaming at you they need it now now now and better yesterday so bend the time and deliver it :hiss:) than I suggest diving into the source code and amending the standard parser so it doesn't report syntax errors, but returns a parsed portion of the string.
strconv.Atoi("10")
to convert a string to integer.strconv.Itoa(10)
to convert an integer to a string. See https://mcmap.net/q/55268/-how-can-i-convert-string-to-integer-in-golang. – Heelandtoe