如何在Go中切割字符串直到特定字符?

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

How to slice string till particular character in Go?

问题

我想提取一个字符串,直到找到某个字符为止。例如:

message := "Rob: Hello everyone!"
user := strings.Trim(message,

我想能够存储"Rob"(读取到找到':'为止)。

英文:

I want to extract a string till a character is found. For example:

message := "Rob: Hello everyone!"
user := strings.Trim(message,

I want to be able to store "Rob" (read till ':' is found).

答案1

得分: 32

你可以使用strings.IndexByte()strings.IndexRune()来获取冒号':'的位置(字节索引),然后简单地使用slice操作来获取string值:

message := "Rob: Hello everyone!"
user := message[:strings.IndexByte(message, ':')]
fmt.Println(user)

输出结果(在Go Playground上尝试):

Rob

如果你不确定冒号是否在字符串中,你需要在进行切片操作之前检查索引,否则会导致运行时错误。你可以这样做:

message := "Rob: Hello everyone!"
if idx := strings.IndexByte(message, ':'); idx >= 0 {
    user := message[:idx]
    fmt.Println(user)
} else {
    fmt.Println("Invalid string")
}

输出结果与上面相同。

将消息更改为无效的情况:

message := "Rob Hello everyone!"

这次的输出结果是(在Go Playground上尝试):

Invalid string

另一个方便的解决方案是使用strings.Split()

message := "Rob: Hello everyone!"

parts := strings.Split(message, ":")
fmt.Printf("%q\n", parts)

if len(parts) > 1 {
    fmt.Println("User:", parts[0])
}

输出结果(在Go Playground上尝试):

["Rob" " Hello everyone!"]
User: Rob

如果输入的字符串中没有冒号,strings.Split()会返回一个包含单个字符串值的字符串切片(在上面的代码中,如果长度为1,则不打印任何内容)。

英文:

You may use strings.IndexByte() or strings.IndexRune() to get the position (byte-index) of the colon ':', then simply slice the string value:

message := "Rob: Hello everyone!"
user := message[:strings.IndexByte(message, ':')]
fmt.Println(user)

Output (try it on the Go Playground):

Rob

If you're not sure the colon is in the string, you have to check the index before proceeding to slice the string, else you get a runtime panic. This is how you can do it:

message := "Rob: Hello everyone!"
if idx := strings.IndexByte(message, ':'); idx >= 0 {
	user := message[:idx]
	fmt.Println(user)
} else {
	fmt.Println("Invalid string")
}

Output is the same.

Changing the message to be invalid:

message := "Rob Hello everyone!"

Output this time is (try it on the Go Playground):

Invalid string

Another handy solution is to use strings.Split():

message := "Rob: Hello everyone!"

parts := strings.Split(message, ":")
fmt.Printf("%q\n", parts)

if len(parts) > 1 {
	fmt.Println("User:", parts[0])
}

Output (try it on the Go Playground):

["Rob" " Hello everyone!"]
User: Rob

Should there be no colon in the input string, strings.Split() returns a slice of strings containing a single string value being the input (the code above does not print anything in that case as length will be 1).

答案2

得分: 6

strings.Indexstrings.IndexRune 可以根据你是否想使用 Unicode 作为分隔符来获取所需字符的索引。

另外,你也可以使用 strings.Split 并获取返回的第一个字符串。

示例:user := strings.Split(message, ":")[0]

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

需要注意的是,如果分隔符字符不在原始字符串中,这种方法不会引发错误,但 user 变量将被设置为原始字符串的全部内容。

英文:

strings.Index or strings.IndexRune, depending on whether you want to use unicode as the separator, will give you the index of the sought character.

Alternatively, you can use strings.Split and just grab the first string returned.

Example: user := strings.Split(message, ":")[0]

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

Notably, this will not panic if the separator character is not in the original string, but the user variable will be set to the entirety of the original string instead.

答案3

得分: 4

其他答案没有提到这一点,但是Go 1.18增加了一个非常方便的strings.Cut函数(https://github.com/golang/go/issues/46336),它可以避免处理索引的需要:

message := "Rob: Hello everyone!"
before, after, found := strings.Cut(message, ":")
fmt.Printf("%q %q %t\n", before, after, found) // "Rob" " Hello everyone!" true

message = "Rob Hello everyone!"
before, after, found = strings.Cut(message, ":")
fmt.Printf("%q %q %t\n", before, after, found) // "Rob Hello everyone!" "" false

Playground)

英文:

The other answers don't mention this, but Go 1.18 saw the addition of a very convenient strings.Cut function, which obviates the need to deal with indices:

message := "Rob: Hello everyone!"
before, after, found := strings.Cut(message, ":")
fmt.Printf("%q %q %t\n", before, after, found) // "Rob" " Hello everyone!" true

message = "Rob Hello everyone!"
before, after, found = strings.Cut(message, ":")
fmt.Printf("%q %q %t\n", before, after, found) // "Rob Hello everyone!" "" false

(Playground)

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

发表评论

匿名网友

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

确定