将带有前导零的编号字符串转换为整数

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

Numbered String to Int with leading zeros

问题

对于一个带有数字的字符串(1234),我通常会使用strconv包中的Atoi函数将字符串转换为整数。然而,如果带有数字的字符串以前导零开头(例如01234),有什么惯用的方法来处理呢?

将字符串切片然后将[]string转换为[]int是一种方法,但这是最好/惯用的Go方式吗?

更新1:
从输入字符串01234,期望输出为任何类型的整数01234(例如简单或组合类型的整数,例如foo := "01234"bar = []int{0, 1, 2, 3, 4})。

是否有一种惯用的(或标准的包函数)方法来解决这个问题,或者当变量有一个或多个前导零(例如0123400001)时,是否需要进行字符串到符文/字节的转换(执行一些业务逻辑,然后再转换回来)。

更新2: 为了完全清楚起见,我可以感觉到问题可以在将来得到澄清:foo,_:= strconv.Atoi("01234")返回一个int类型的1234(并且可以使用strings包等其他方式获得相同的结果)。

这里的问题是,如何(如果可能的话,以Go的惯用方式)获得带有前导零的结果,即01234(而不是1234),并且类型为int

英文:

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?

答案1

得分: 1

使用strings.TrimLeft(s, "0")来从字符串中删除前导零。

英文:

use strings.TrimLeft(s, "0") to remove leading zeroes from the string.

答案2

得分: 1

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

你可以在这个链接中找到更多关于fmt包的信息:https://pkg.go.dev/fmt#pkg-overview

英文:
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

答案3

得分: 0

将一个包含十进制数字的字符串转换为整数切片,可以通过循环遍历字符串,并使用减法将符文转换为相应的整数:

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
}

示例用法:

foo := "01234"
bar, _ := toIntSlice(foo)
// bar is []int{0, 1, 2, 3, 4}

链接:https://go.dev/play/p/etHtApYoWUi

英文:

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 &lt; &#39;0&#39; || r &gt; &#39;9&#39; {
			return nil, fmt.Errorf(&quot;not an integer %s&quot;, s)
		}
		result = append(result, int(r-&#39;0&#39;))
	}
	return result, nil
}

Example use:

foo := &quot;01234&quot; 
bar, _ := toIntSlice(foo)
// bar is []int{0, 1, 2, 3, 4}

https://go.dev/play/p/etHtApYoWUi

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

发表评论

匿名网友

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

确定