删除分隔符后的所有内容

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

TrimRight everything after delimiter

问题

我有一个转换为字符串的float64值:30.060671

我试图删除30后面的所有内容。

我尝试过以下一些方法:

fmt.Println(strings.TrimRight("30.060671", ".([0-9])"))
fmt.Println(strings.TrimRight("30.060671", "."))
fmt.Println(strings.TrimSuffix("30.060671", "."))
英文:

I have a float64 I converted into a string: 30.060671

I'm trying to trim/remove/chomp everything after 30

Some of the things I've tried:

fmt.Println(strings.TrimRight("30.060671", ".([0-9])"))
fmt.Println(strings.TrimRight("30.060671", "."))
fmt.Println(strings.TrimSuffix("30.060671", "."))

答案1

得分: 29

一种方法是使用 strings.Split 函数来分割句点:

parts := strings.Split("30.060671", ".")
fmt.Println(parts[0])

另一种选项是先将数字转换为整数,然后再转换为字符串:

a := 30.060671
b := int(a)
fmt.Println(b)
英文:

One way to do it would be to use strings.Split on the period:

parts := strings.Split("30.060671", ".")
fmt.Println(parts[0])

Another option is to convert to an int first and then to a string:

a := 30.060671
b := int(a)    
fmt.Println(b)

答案2

得分: 11

根据@pайтфол德在评论中的建议,你应该在转换为字符串之前将浮点数四舍五入。

无论如何,这是我使用strings.Index来修剪从.开始的剩余部分的尝试:

func trimStringFromDot(s string) string {
    if idx := strings.Index(s, "."); idx != -1 {
        return s[:idx]
    }
    return s
}

Playground

此外,为了回答为什么TrimRightTrimSuffix不能按预期工作的问题,是因为.不是一个尾部字符串/Unicode:

TrimRight返回字符串s的一个切片,其中包含所有尾部的Unicode码点。

TrimSuffix返回不包含提供的尾部后缀字符串的s。如果s不以后缀结尾,则返回s本身。

英文:

As per @pайтфолд suggested in comment, you should have rounded the float before converting to string.

Anyway, here is my attempt using strings.Index to trim the remaining from .:

func trimStringFromDot(s string) string {
	if idx := strings.Index(s, "."); idx != -1 {
		return s[:idx]
	}
	return s
}

Playground

Also, to answer why TrimRight and TrimSuffix not working as expected is because . is not a trailing string/unicode:

> TrimRight returns a slice of the string s, with all trailing Unicode
> code points contained in cutset removed.
>
> TrimSuffix returns s without the provided trailing suffix string. If s
> doesn't end with suffix, s is returned unchanged.

答案3

得分: 5

这是如何获取分隔符两侧内容的方法。

在 Go 1.18 之后,可以使用 strings.Cut

string := "Symver.0.1.0"
delimiter := "."

leftOfDelimiter, rightOfDelimiter, found := strings.Cut(string, delimiter)

fmt.Println("分隔符左侧内容:", leftOfDelimiter)
fmt.Println("分隔符右侧内容:", rightOfDelimiter)
fmt.Println("是否找到分隔符:", found)

//分隔符左侧内容: Symver
//分隔符右侧内容: 0.1.0
//是否找到分隔符: true

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

在 Go 1.18 之前,可以使用以下方法:

string := "Symver.0.1.0"
delimiter := "."

leftOfDelimiter := strings.Split(string, delimiter)[0]
rightOfDelimiter := strings.Join(strings.Split(string, delimiter)[1:], delimiter)

fmt.Println("分隔符左侧内容:", leftOfDelimiter)
fmt.Println("分隔符右侧内容:", rightOfDelimiter)

//分隔符左侧内容: Symver
//分隔符右侧内容: 0.1.0

https://play.golang.org/p/HBi4G5tBL9

英文:

Here is how to get either side of a delimiter.

After Go.18 use strings.Cut

string := "Symver.0.1.0"
delimiter := "."

leftOfDelimiter, rightOfDelimiter, found := strings.Cut(string, delimiter)

fmt.Println("Left of Delimiter: ", leftOfDelimiter)
fmt.Println("Right of Delimiter: ", rightOfDelimiter)
fmt.Println("Found: ", found)

//Left of Delimiter:  Symver
//Right of Delimiter:  0.1.0
//Found:  true

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

Before Go1.18

string := "Symver.0.1.0"
delimiter := "."

leftOfDelimiter := strings.Split(string, delimiter)[0]
rightOfDelimiter := strings.Join(strings.Split(string, delimiter)[1:], delimiter)

fmt.Println("Left of Delimiter: ", leftOfDelimiter)
fmt.Println("Right of Delimiter: ", rightOfDelimiter)	

//Left of Delimiter:  Symver
//Right of Delimiter:  0.1.0

https://play.golang.org/p/HBi4G5tBL9

答案4

得分: 1

Go提供了一个函数来实现这个功能:strings.Cut

before, after, found := strings.Cut("123.456", ".")

你可以只使用before并忽略其他的部分:

before, _, _ := strings.Cut("123.456", ".")
英文:

Go provides a function for this: strings.Cut

before,after,found := strings.Cut("123.456", ".")

You can just use before and ignore the rest:

before,_,_ := strings.Cut("123.456", ".")

答案5

得分: 0

fmt.Println(fmt.Sprintf("%.0f", 30.060671))

这样就可以轻松完成了。(顺便说一句其中一位评论者最初提到或暗示了类似的解决方案)。
然而如果你只能使用字符串可以这样做 -

fmt.Println(fmt.Sprintf("%.0f", 30.060671))
value := "30.060671"
f := func(c rune) bool {
    return c == ',' || c == ':' || c == '.'
}
fields := strings.FieldsFunc(value, f)[0]
fmt.Printf("%v", fields)

你可以选择分隔符我不知道这是否优雅但嘿
英文:
fmt.Println(fmt.Sprintf("%.0f", 30.060671))

That oughtta do it easy. (BTW: Just to add, one of the commenters originally stated or alluded to a similar solution).
However must you only use string, this should do -

   fmt.Println(fmt.Sprintf("%.0f", 30.060671))
	value := "30.060671"
	f := func(c rune) bool {
		return c == ',' || c == ':' || c == '.'
		}
	 fields := strings.FieldsFunc(value, f)[0]
	fmt.Printf("%v", fields)

You have choice of delimiters there. I don't know if this is elegant but hey.

huangapple
  • 本文由 发表于 2015年4月12日 01:57:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/29581165.html
匿名

发表评论

匿名网友

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

确定