英文:
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.Index 或 strings.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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论