英文:
How to find a character index in Golang?
问题
我正在尝试在Go语言中找到字符串中的"@"字符,但是我找不到方法来实现。我知道如何索引字符,比如"HELLO1"会输出"E"。然而,我想找到找到字符的索引号。
在Python中,我会这样做:
x = "chars@arefun"
split = x.find("@")
chars = x[:split]
arefun = x[split+1:]
print(split)
print(chars)
print(arefun)
这样,chars将返回"chars",arefun将返回"arefun",使用"@"作为分隔符。我已经尝试了几个小时,但是在Golang中似乎找不到合适的方法来实现这个。
英文:
I'm trying to find "@" string character in Go but I cannot find a way to do it. I know how to index characters like "HELLO1" which would output "E". However I'm trying to find index number of the found char.
In Python I'd do it in following way:
x = "chars@arefun"
split = x.find("@")
chars = x[:split]
arefun = x[split+1:]
>>>print split
5
>>>print chars
chars
>>>print arefun
arefun
So chars would return "chars" and arefun would return "arefun" while using "@" delimeter. I've been trying to find solution for hours and I cannot seem to find proper way to do it in Golang.
答案1
得分: 94
你可以使用strings
包的Index函数。
Playground: https://play.golang.org/p/_WaIKDWCec
package main
import "fmt"
import "strings"
func main() {
x := "chars@arefun"
i := strings.Index(x, "@")
fmt.Println("Index: ", i)
if i > -1 {
chars := x[:i]
arefun := x[i+1:]
fmt.Println(chars)
fmt.Println(arefun)
} else {
fmt.Println("Index not found")
fmt.Println(x)
}
}
英文:
You can use the Index function of package strings
Playground: https://play.golang.org/p/_WaIKDWCec
package main
import "fmt"
import "strings"
func main() {
x := "chars@arefun"
i := strings.Index(x, "@")
fmt.Println("Index: ", i)
if i > -1 {
chars := x[:i]
arefun := x[i+1:]
fmt.Println(chars)
fmt.Println(arefun)
} else {
fmt.Println("Index not found")
fmt.Println(x)
}
}
答案2
得分: 6
如果您正在搜索非ASCII字符(非英语语言),您需要使用http://golang.org/x/text/search。
func SubstringIndex(str string, substr string) (int, bool) {
m := search.New(language.English, search.IgnoreCase)
start, _ := m.IndexString(str, substr)
if start == -1 {
return start, false
}
return start, true
}
index, found := SubstringIndex('Aarhus', 'Å');
if found {
fmt.Println("匹配开始于", index);
}
在这里搜索language.Tag
结构以找到您希望进行搜索的语言,如果不确定,可以使用language.Und
。
英文:
If you are searching for non-ASCII characters (languages other than english) you need to use http://golang.org/x/text/search.
func SubstringIndex(str string, substr string) (int, bool) {
m := search.New(language.English, search.IgnoreCase)
start, _ := m.IndexString(str, substr)
if start == -1 {
return start, false
}
return start, true
}
index, found := SubstringIndex('Aarhus', 'Å');
if found {
fmt.Println("match starts at", index);
}
Search the language.Tag
structs here to find the language you wish to search with or use language.Und
if you are not sure.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论