How can I convert string to integer in golang

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

How can I convert string to integer in golang

问题

在Go语言中,你可以使用strconv.Atoi()函数将字符串转换为整数。它会自动忽略字符串中的非数字字符,并返回转换后的整数值。例如:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "10"
	num, err := strconv.Atoi(str)
	if err == nil {
		fmt.Println(num) // 输出:10
	}

	str = "65.0"
	num, err = strconv.Atoi(str)
	if err == nil {
		fmt.Println(num) // 输出:65
	}

	str = "xx"
	num, err = strconv.Atoi(str)
	if err == nil {
		fmt.Println(num) // 输出:0
	}

	str = "11xx"
	num, err = strconv.Atoi(str)
	if err == nil {
		fmt.Println(num) // 输出:11
	}

	str = "xx11"
	num, err = strconv.Atoi(str)
	if err == nil {
		fmt.Println(num) // 输出:0
	}
}

使用strconv.Atoi()函数可以方便地将字符串转换为整数,它会自动处理不同格式的字符串。如果转换失败,它会返回一个错误。你可以根据需要在代码中进行错误处理。希望这可以帮助到你!

英文:

I want to convert string to integer in golang. But I don't know the format of string. For example, "10" -> 10, "65.0" -> 65, "xx" -> 0, "11xx" -> 11, "xx11"->0

I do some searching and find strconv.ParseInt(). But it can not handle "65.0". So I have to check string's format.

Is there a better way?

答案1

得分: 11

我相信你正在寻找的函数是 strconv.ParseFloat(),你可以在这里看到示例链接。但是这个函数的返回类型是 float64

如果你不需要将字符串转换为浮点数后的小数部分,可以使用以下函数:

func StrToInt(str string) (int, error) {
    nonFractionalPart := strings.Split(str, ".")
    return strconv.Atoi(nonFractionalPart[0])
}
英文:

I believe function you are looking for is

strconv.ParseFloat()

see example here

But return type of this function is float64.

If you don't need fractional part of the number passed as the string following function would do the job:

func StrToInt(str string) (int, error) {
    nonFractionalPart := strings.Split(str, ".")
    return strconv.Atoi(nonFractionalPart[0])
}

答案2

得分: 9

你可以使用这三个函数将字符串值转换为整数或浮点数。

注意:必须导入strconv内置包才能执行这些函数。

  1. func Atoi(s string) (int, error)
  2. func ParseInt(s string, base int, bitSize int) (i int64, err error)
  3. func ParseFloat(s string, bitSize int) (float64, error)

<!-- -->

package main

import (
	"fmt"
	"strconv"
)

func main() {
	i, _ := strconv.Atoi("-42")
	fmt.Println(i)

	j,_ := strconv.ParseInt("-42", 10, 8)
 	fmt.Println(j)

	k,_ := strconv.ParseFloat("-42.8", 8)
	fmt.Println(k)
}
英文:

You can use these three functions to convert a string value to an integer or a float.

Note: the strconv builtin package must be imported to execute these functions.

  1. func Atoi(s string) (int, error)
  2. func ParseInt(s string, base int, bitSize int) (i int64, err error)
  3. func ParseFloat(s string, bitSize int) (float64, error)

<!-- -->

package main

import (
	&quot;fmt&quot;
	&quot;strconv&quot;
)

func main() {
	i, _ := strconv.Atoi(&quot;-42&quot;)
	fmt.Println(i)

	j,_ := strconv.ParseInt(&quot;-42&quot;, 10, 8)
 	fmt.Println(j)

	k,_ := strconv.ParseFloat(&quot;-42.8&quot;, 8)
	fmt.Println(k)
}

答案3

得分: 5

package main

import "strconv"
import "fmt"

// 内置的 "strconv" 包提供了数字解析。

// 对于 `ParseInt`,`0` 表示从字符串中推断基数。`64` 要求结果适应 64 位。

value, err := strconv.ParseInt("123", 0, 64)
if err != nil {
    panic(err)
}
fmt.Println(value)

参考链接,点击这里

如果你总是想要相同的结果,也可以传递一个非零的基数(比如 10)。

英文:
package main

import &quot;strconv&quot;
import &quot;fmt&quot;

// The built-in package &quot;strconv&quot; provides the number parsing.

// For `ParseInt`, the `0` means infer the base from
// the string. `64` requires that the result fit in 64
// bits.


value, err := strconv.ParseInt(&quot;123&quot;, 0, 64)
if err != nil {
    panic(err)
}
fmt.Println(value)

For reference, Click Here

You can also pass a non-zero base (like 10) if you always want the same thing.

答案4

得分: 2

我想在golang中将字符串转换为整数。

正如你已经提到的,有一个strconv.ParseInt函数可以做到这一点!

但是我不知道字符串的格式。

听起来有点可怕(和具有挑战性),但是在看了你的示例之后,我可以很容易地得出结论,你知道格式,问题可以陈述如下:

如何将字符串的初始部分解析为整数?

由于strconv.ParseInt在语法错误时返回0,它不是一个很好的选择;至少不是直接的选择。但是它可以解析你的初始部分,如果你将它_提取_出来的话。我相信你已经想到了,但这确实是最清晰的解决方案:从字符串中提取你的内容,然后进行解析。

你可以通过几种方式提取前导整数,其中一种方式是使用regexp

package main

import (
	"fmt"
	"regexp"
	"strconv"
)

// 提取你需要的内容
var leadingInt = regexp.MustCompile(`^[-+]?\d+`)

func ParseLeadingInt(s string) (int64, error) {
	s = leadingInt.FindString(s)
	if s == "" { // 如果你不想在"xx"等情况下报错,可以添加这个判断
		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)
	}
}

我相信这段代码简单明了地展示了意图。你还在使用标准的ParseInt,它_有效_并提供了你所需的所有错误检查。

如果由于任何原因你不能提取前导整数(你需要快速解析大量数据并且你的老板在对你大喊大叫,他们现在需要它,现在现在,最好是昨天,所以快点弄出来),那么我建议深入研究源代码,修改标准解析器,使其不报告语法错误,而是返回解析的字符串部分。

英文:

> 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 (
	&quot;fmt&quot;
	&quot;regexp&quot;
	&quot;strconv&quot;
)

// Extract what you need
var leadingInt = regexp.MustCompile(`^[-+]?\d+`)

func ParseLeadingInt(s string) (int64, error) {
	s = leadingInt.FindString(s)
	if s == &quot;&quot; { // add this if you don&#39;t want error on &quot;xx&quot; etc
		return 0, nil
	}
	return strconv.ParseInt(s, 10, 64)
}

func main() {
	for _, s := range []string{&quot;10&quot;, &quot;65.0&quot;, &quot;xx&quot;, &quot;11xx&quot;, &quot;xx11&quot;} {
		i, err := ParseLeadingInt(s)
		fmt.Printf(&quot;%s\t%d\t%v\n&quot;, 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.

答案5

得分: 2

为了补充@MayankPatel和@DeepakG的出色答案,一个字符串可以转换为各种数值类型,各种数值类型也可以转换为字符串。同样,"true"可以转换为布尔值,true也可以转换为字符串。

package main

import (
	"fmt"
	"strconv"
)

func main() {
	//将字符串转换为其他类型
	f, _ := strconv.ParseFloat("70.99", 64)
	i, _ := strconv.Atoi(fmt.Sprintf("%.f", f))
	t, _ := strconv.ParseBool("true")
	c := []interface{}{[]byte("70.99"), f, i, rune(i), t}
	checkType(c) //[]uint8 [55 48 46 57 57], float64 70.99, int 71, int32 71, bool true

	//将其他类型转换为字符串
	c = []interface{}{fmt.Sprintf("%s", []byte("70.99")), fmt.Sprintf("%.f", f), strconv.Itoa(i), string(rune(i)), strconv.FormatBool(t)}
	checkType(c) //string 70.99, string 71, string 71, string G, string true
}

func checkType(s []interface{}) {
	for k, _ := range s {
		fmt.Printf("%T %v\n", s[k], s[k])
	}
}

字符串类型表示一组字符串值。字符串值是一个(可能为空的)字节序列。字节的数量称为字符串的长度,长度永远不会为负数。字符串是不可变的。请参阅https://Golang.org/ref/spec#String_types。

以下是将字符串解析为整数的三种方法,从运行时间最快到最慢:1. strconv.ParseInt(...) 最快 2. strconv.Atoi(...) 仍然非常快 3. fmt.Sscanf(...) 不是非常快,但最灵活。请参阅https://stackoverflow.com/a/47317150/12817546。

避免将字符串转换为[]byte:b := []byte(s)。它会分配一个新的内存空间,并将整个内容复制到其中。请参阅https://stackoverflow.com/a/52943136/12817546。请参阅https://stackoverflow.com/a/41460993/12817546。引号已编辑。

英文:

To add to the excellent answer by @MayankPatel and by @DeepakG. A string can be set to various numeric types. Various numeric types can be set to a string. Likewise, "true" can be set to a bool and true can be set to a string.

package main

import (
	&quot;fmt&quot;
	&quot;strconv&quot;
)

func main() {
	//convert a string to another type
	f, _ := strconv.ParseFloat(&quot;70.99&quot;, 64)
	i, _ := strconv.Atoi(fmt.Sprintf(&quot;%.f&quot;, f))
	t, _ := strconv.ParseBool(&quot;true&quot;)
	c := []interface{}{[]byte(&quot;70.99&quot;), f, i, rune(i), t}
	checkType(c) //[]uint8 [55 48 46 57 57], float64 70.99, int 71, int32 71, bool true

	//convert another type to a string
	c = []interface{}{fmt.Sprintf(&quot;%s&quot;, []byte(&quot;70.99&quot;)), fmt.Sprintf(&quot;%.f&quot;, f), strconv.Itoa(i), string(rune(i)), strconv.FormatBool(t)}
	checkType(c) //string 70.99, string 71, string 71, string G, string true
}

func checkType(s []interface{}) {
	for k, _ := range s {
		fmt.Printf(&quot;%T %v\n&quot;, s[k], s[k])
	}
}

A string type represents the set of string values. A string value is a (possibly empty) sequence of bytes. The number of bytes is called the length of the string and is never negative. Strings are immutable. See https://Golang.org/ref/spec#String_types.

Here are three ways to parse strings into integers, from fastest runtime to slowest: 1. strconv.ParseInt(...) fastest 2. strconv.Atoi(...) still very fast 3. fmt.Sscanf(...) not terribly fast but most flexible. See https://stackoverflow.com/a/47317150/12817546.

Avoid converting a string to []byte: b := []byte(s). It allocates a new memory space and copies the whole content into it. See https://stackoverflow.com/a/52943136/12817546. See https://stackoverflow.com/a/41460993/12817546. Quotes edited.

答案6

得分: 1

你可以编写一个FieldsFunc函数来解析并单独获取数字值。

在这里运行代码

package main

import (
	"fmt"
	"strconv"
	"strings"
	"unicode"
)

func stripNonIntFloat(s string) string {
	f := func(c rune) bool {
		return !unicode.IsNumber(c) && (c != 46)
	}
	output := strings.FieldsFunc(s, f)
	if len(output) > 0 {
		return output[0]
	} else {
		return ""
	}
}

func main() {
	strList := []string{"10", "65.0", "xx", "11xx", "xx11"}
	for i := 0; i < len(strList); i++ {
		s := stripNonIntFloat(strList[i])
		v, err := strconv.ParseFloat(s, 10)
		if err != nil {
			fmt.Println(strList[i], 0)
		} else {
			fmt.Println(strList[i], v)
		}
	}
}

这里的输出结果是:

10 10
65.0 65
xx 0
11xx 11
xx11 11

请注意,最后一个条件xx11被处理为11

英文:

You can write a FieldsFunc to parse and get the number values alone separately.

Play it here

package main

import (
	&quot;fmt&quot;
	&quot;strconv&quot;
	&quot;strings&quot;
	&quot;unicode&quot;
)

func stripNonIntFloat(s string) string {
	f := func(c rune) bool {
		return !unicode.IsNumber(c) &amp;&amp; (c != 46)
	}
	output := strings.FieldsFunc(s, f)
	if len(output) &gt; 0 {
		return output[0]
	} else {
		return &quot;&quot;
	}
}

func main() {
	strList := []string{&quot;10&quot;, &quot;65.0&quot;, &quot;xx&quot;, &quot;11xx&quot;, &quot;xx11&quot;}
	for i := 0; i &lt; len(strList); i++ {
		s := stripNonIntFloat(strList[i])
		v, err := strconv.ParseFloat(s, 10)
		if err != nil {
			fmt.Println(strList[i], 0)
		} else {
			fmt.Println(strList[i], v)
		}
	}
}

The output here is

10 10
65.0 65
xx 0
11xx 11
xx11 11

Note that your last condition of xx11 handles it as 11.

答案7

得分: 1

从字符串的开头提取一个整数是我经常做的事情之一。在C语言中,你可以使用atoi()或strtol()函数。令人荒谬的是,Go语言没有标准库函数来完成这个任务。不管怎样,这里是我刚刚写的一个函数:

// StrToInt从字符串的开头获取整数。
// 它返回值和第一个非数字字符的偏移量。
func StrToInt(s string) (v int, offset int) {
    offset = strings.IndexFunc(s, func(r rune) bool { return r < '0' || r > '9' })
    if offset == -1 { offset = len(s) }
    if offset == 0 { return }   // 避免对空字符串使用Atoi函数
    v, _ = strconv.Atoi(s[:offset])
    return
}

如果你想处理负整数,你需要稍作修改。

英文:

Extracting an int from the start of a string is one of the most common things I do. In C you can use atoi() or strtol(). It's ridiculous that Go does not have a std library function to do it. Anyway here is one I just rolled up:

// strToInt gets the integer from the start of the string.
// It returns the value and the offset of the first non-digit.
func StrToInt(s string) (v int, offset int) {
    offset = strings.IndexFunc(s, func(r rune) bool { return r &lt; &#39;0&#39; || r &gt; &#39;9&#39; })
    if offset == -1 { offset = len(s) }
    if offset == 0 { return }   // Avoid Atoi on empty string
    v, _ = strconv.Atoi(s[:offset])
    return
}

You'll need a slight fix if you want to handle -ve integers.

答案8

得分: 0

我的当前解决方案是:

// 将字符串转换为整数,尽力而为。
// TODO:处理溢出并添加单元测试
func StrToInt(str string) (int64, error) {
    if len(str) == 0 {
        return 0, nil
    }
    negative := false
    i := 0
    if str[i] == '-' {
        negative = true
        i++
    } else if str[i] == '+' {
        i++
    }
    r := int64(0)
    for ; i < len(str); i++ {
        if unicode.IsDigit(rune(str[i])) {
            r = r*10 + int64(str[i]-'0')
        } else {
            break
        }
    }
    if negative {
        r = -r
    }
    // TODO: 如果 i < len(str),我们应该返回错误
    return r, nil
}

请注意,这只是一个初步的实现,还需要处理溢出情况并添加单元测试。

英文:

My current solution is:

// Convert string to integer in best effort.                                                                                
 // TODO: handle overflow and add unittest                                                                                   
func StrToInt(str string) (int64, error) {                                                                                  
    if len(str) == 0 {                                                                                                      
        return 0, nil                                                                                                       
     }                                                                                                                       
     negative := false                                                                                                       
     i := 0                                                                                                                  
     if str[i] == &#39;-&#39; {                                                                                                      
         negative = true                                                                                                     
         i++                                                                                                                 
     } else if str[i] == &#39;+&#39; {                                                                                               
         i++                                                                                                                 
     }                                                                                                                       
     r := int64(0)                                                                                                           
     for ; i &lt; len(str); i++ {                                                                                             
         if unicode.IsDigit(rune(str[i])) {                                                                                  
             r = r*10 + int64(str[i]-&#39;0&#39;)                                                                                    
         } else {
             break
          }                                                                                                                   
     }                                                                                                                       
     if negative {                                                                                                           
         r = -r                                                                                                              
     }                                                                                                                       
     // TODO: if i &lt; len(str), we should return error                                                                        
     return r, nil                                                                                                           
 }    

答案9

得分: 0

import (
    "strconv"
    "strings"
)

func StrToInt(str string) int {
    // 从字符串中删除任何非数字字符
    str = strings.TrimFunc(str, func(r rune) bool {
        return r < '0' || r > '9'
    })

    // 将清理后的字符串转换为整数
    n, _ := strconv.Atoi(str)
    return n
}

这是一个Go语言的代码片段,它定义了一个名为StrToInt的函数,该函数将字符串转换为整数。它的实现逻辑是先删除字符串中的非数字字符,然后将清理后的字符串转换为整数。

英文:
import (
  &quot;strconv&quot;
  &quot;strings&quot;
)

func StrToInt(str string) int {
  // Delete any non-numeric character from the string
  str = strings.TrimFunc(str, func(r rune) bool {
      return r &lt; &#39;0&#39; || r &gt; &#39;9&#39;
  })

  // Convert the cleaned-up string to an integer
  n, _ := strconv.Atoi(str)
  return n
}

huangapple
  • 本文由 发表于 2015年7月18日 12:08:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/31487694.html
匿名

发表评论

匿名网友

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

确定