我有以0开头的字符串。需要获取前导零的数量: 像这样:
func LeadZeros(num string) int{
// count the leading zeros
return leadZerosNumber
}
LeadZeros("0012") --> 2
LeadZeros("5") --> 0
LeadZeros("05") --> 1
LeadZeros("0") --> 0 (1 also good)
LeadZeros("00") --> 1 (2 also good)
寻找嵌入在go中的内容(或非常短的格式)
例如,用于书写的内容是:strings.Repeat(“ 0”,3)
答案 0 :(得分:3)
func LeadZeros(num string) int {
i := 0
for ;i < len(num) && num[i] == '0'; i++ {
}
return i
}
有很多方法可以做到这一点,我建议您最容易理解。这是另一种形式:
func LeadZeros(num string) int {
return len(num) - len(strings.TrimLeft(num, "0"))
}
答案 1 :(得分:1)
func LeadZeros(num string) int{
leadZerosNumber := 0
for leadZerosNumber < len(num) && num[leadZerosNumber] == '0' {
leadZerosNumber++
}
return leadZerosNumber
}
您可以检查playground上的所有完整代码
要调整代码以输出这些情况:
LeadZeros(“ 0”)-> 0
LeadZeros(“ 00”)-> 1
只需将条件从leadZerosNumber < len(num) && num[leadZerosNumber] == '0'
更改为leadZerosNumber < len(num) - 1 && num[leadZerosNumber] == '0'
答案 2 :(得分:0)
package main
import (
"fmt"
)
func main() {
yourString := "0012"
fmt.Println("Number Of Initial 0 = ", leadZeros(yourString))
}
func leadZeros(num string) (leadZerosNumber int) {
for index := range num {
if string(num[index]) == "0" {
leadZerosNumber++
} else {
break
}
}
return leadZerosNumber
}
答案 3 :(得分:0)
package main
import "fmt"
func main(){
fmt.Println(LeadingZeros("0010"))
}
func LeadingZeros(s string) int {
c:=0
for _,v := range s {
if v=='0'{
c++
}else{
break
}
}
return c
}
答案 4 :(得分:-1)
使用正则表达式:
func LeadingZeros(str string) int {
re := regexp.MustCompile("^0.*")
match := re.FindString(str)
return len(match)
}