检查字符串是否为整数。

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

Check if string is int

问题

在Go语言中,你可以使用strconv.Atoi函数将字符串转换为整数,并通过检查返回的错误来确定字符串是否为整数。以下是一个示例代码:

import (
    "fmt"
    "strconv"
)

func isInt(s string) bool {
    _, err := strconv.Atoi(s)
    return err == nil
}

func main() {
    v := "4"
    if isInt(v) {
        fmt.Println("我们有一个整数,可以安全地使用strconv进行类型转换")
    }
}

注意:strconv.Atoi函数在将字符串转换为整数时,如果字符串中包含非数字字符,会返回一个错误。你可以通过检查错误是否为nil来确定字符串是否为整数。

英文:

How can I check if a string value is an integer or not in Go?

Something like

v := "4"
if isInt(v) {
  fmt.Println("We have an int, we can safely cast this with strconv")
}

Note: I know that strconv.Atoi returns an error, but is there any other function to do this?

<s>The problem with strconv.Atoi is that it will return 7 for &quot;a7&quot;</s>

答案1

得分: 195

根据你的说法,你可以使用strconv.Atoi来实现这个功能。

if _, err := strconv.Atoi(v); err == nil {
    fmt.Printf("%q 看起来像一个数字。\n", v)
}

你可以使用scanner.Scanner(来自text/scanner包)以ScanInts模式,或者使用正则表达式来验证字符串,但是Atoi是最合适的工具。

英文:

As you said, you can use strconv.Atoi for this.

if _, err := strconv.Atoi(v); err == nil {
    fmt.Printf(&quot;%q looks like a number.\n&quot;, v)
}

You could use scanner.Scanner (from text/scanner) in mode ScanInts, or use a regexp to validate the string, but Atoi is the right tool for the job.

答案2

得分: 35

这是更好的,你可以检查64位(或更少)的整数。

strconv.Atoi只支持32位。

如果 _, err := strconv.ParseInt(v,10,64); err == nil {
fmt.Printf("%q 看起来像一个数字。\n", v)
}

尝试一下 v := "12345678900123456789"。

英文:

this is better, you can check for ints upto 64 ( or less ) bits

strconv.Atoi only supports 32 bits

if _, err := strconv.ParseInt(v,10,64); err == nil {
    fmt.Printf(&quot;%q looks like a number.\n&quot;, v)
}

try it out with v := "12345678900123456789"

答案3

得分: 17

你可以使用unicode.IsDigit()函数:

import "unicode"

func isInt(s string) bool {
    for _, c := range s {
        if !unicode.IsDigit(c) {
            return false
        }
    }
    return true
}
英文:

You can use unicode.IsDigit():

import &quot;unicode&quot;

func isInt(s string) bool {
	for _, c := range s {
		if !unicode.IsDigit(c) {
			return false
		}
	}
	return true
}

答案4

得分: 13

你可以使用govalidator

代码

govalidator.IsInt("123")  // true

<br/>

完整示例

package main

import (
    "fmt"
    valid "github.com/asaskevich/govalidator"
)

func main() {
    fmt.Println("是否为整数?", valid.IsInt("978"))
}

输出:

$ go run intcheck.go
是否为整数? true
英文:

You can use govalidator.

Code

govalidator.IsInt(&quot;123&quot;)  // true

<br/>

Full Example

package main

import (
    &quot;fmt&quot;
    valid &quot;github.com/asaskevich/govalidator&quot;
)

func main() {
    fmt.Println(&quot;Is it a Integer? &quot;, valid.IsInt(&quot;978&quot;))
}

Output:

$ go run intcheck.go
Is it a Integer?  true

答案5

得分: 10

你也可以使用正则表达式来检查这个。

这可能有点过度,但如果你想扩展你的规则,它也会给你更多的灵活性。

这里是一些代码示例:

package main

import (
	"regexp"
)

var digitCheck = regexp.MustCompile(`^[0-9]+$`)

func main() {
	digitCheck.MatchString("1212")
}

如果你想看它运行:https://play.golang.org/p/6JmzgUGYN3u

希望能帮到你 检查字符串是否为整数。

英文:

You might also use regexp to check this.

It can be a little overkill, but it also gives you more flexibility if you want to extend your rules.

Here some code example:

package main

import (
	&quot;regexp&quot;
)

var digitCheck = regexp.MustCompile(`^[0-9]+$`)

func main() {
	digitCheck.MatchString(&quot;1212&quot;)
}

If you want to see it running: https://play.golang.org/p/6JmzgUGYN3u

Hope it helps 检查字符串是否为整数。

答案6

得分: 3

这个函数会逐个检查字符,看它是否在0到9之间。

func IsDigitsOnly(s string) bool {
    for _, c := range s {
        if c < '0' || c > '9' {
            return false
        }
    }
    return true
}
英文:

This manually checks each CHAR to see if it falls between 0 and 9.

func IsDigitsOnly(s string) bool {
    for _, c := range s {
	    if c &lt; &#39;0&#39; || c &gt; &#39;9&#39; {
		    return false
	    }
    }
    return true
}

答案7

得分: 1

这可能会有所帮助

func IsInt(s string) bool {
    l := len(s)
    if strings.HasPrefix(s, "-") {
        l = l - 1
        s = s[1:]
    }

    reg := fmt.Sprintf("\\d{%d}", l)

    rs, err := regexp.MatchString(reg, s)

    if err != nil {
        return false
    }

    return rs
}
英文:

this might help

func IsInt(s string) bool {
	l := len(s)
	if strings.HasPrefix(s, &quot;-&quot;) {
		l = l - 1
		s = s[1:]
	}

	reg := fmt.Sprintf(&quot;\\d{%d}&quot;, l)

	rs, err := regexp.MatchString(reg, s)

	if err != nil {
		return false
	}

	return rs
}

答案8

得分: 1

你可以检查所有的符文是否在0到9之间。

isNotDigit := func(c rune) bool { return c < '0' || c > '9' }
b := strings.IndexFunc(s, isNotDigit) == -1

英文:

you can check if all runes are between 0 and 9

isNotDigit := func(c rune) bool { return c &lt; &#39;0&#39; || c &gt; &#39;9&#39; }
b := strings.IndexFunc(s, isNotDigit) == -1

答案9

得分: 1

如果你的字符串输入可能具有任意长度,请小心处理。

在需要检查超长字符串长度的情况下,strconv 方法是无用的,它会产生一个 ErrRange 错误。

对于这种情况,你可以使用以下代码:

s := strings.TrimSpace(val)

r := regexp.MustCompile(`^\d+$`)

isNum := r.Match([]byte(s))

这段代码可以用来检查字符串 val 是否只包含数字。

英文:

be careful if your strings input could be in any length.

in cases where you have to check for monster strings length the strconv approach is useless. it will produce an ErrRange error.

for such scenarios:

s := strings.TrimSpace(val)

r := regexp.MustCompile(`^\d+$`)

isNum := r.Match([]byte(s))

答案10

得分: -1

大部分上面发布的解决方案都很简洁和好用。

以下是一个简单的解决方案,不使用任何库:

func IsNumericOnly(str string) bool {

	if len(str) == 0 {
		return false
	}

	for _, s := range str {
		if s < '0' || s > '9' {
			return false
		}
	}
	return true
}

测试用例:

func TestIsNumericOnly(t *testing.T) {
	cases := []struct {
		name      string
		str       string
		isNumeric bool
	}{
		{
			name:      "numeric string",
			str:       "0123456789",
			isNumeric: true,
		},
		{
			name:      "not numeric string",
			str:       "#0123456789",
			isNumeric: false,
		},
	}

	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			assert.Equal(t, c.isNumeric, IsNumericOnly(c.str))
		})
	}
}
英文:

Most of the above posted solutions are neat and nice.

Below is a simple solution without using any library:

func IsNumericOnly(str string) bool {

	if len(str) == 0 {
		return false
	}

	for _, s := range str {
		if s &lt; &#39;0&#39; || s &gt; &#39;9&#39; {
			return false
		}
	}
	return true
}

Test cases

func TestIsNumericOnly(t *testing.T) {
	cases := []struct {
		name      string
		str       string
		isNumeric bool
	}{
		{
			name:      &quot;numeric string&quot;,
			str:       &quot;0123456789&quot;,
			isNumeric: true,
		},
		{
			name:      &quot;not numeric string&quot;,
			str:       &quot;#0123456789&quot;,
			isNumeric: false,
		},
	}

	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			assert.Equal(t, c.isNumeric, IsNumericOnly(c.str))
		})
	}
}

huangapple
  • 本文由 发表于 2014年3月23日 23:58:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/22593259.html
匿名

发表评论

匿名网友

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

确定