【问题标题】:How to find a character index in Golang?如何在 Golang 中找到字符索引?
【发布时间】:2013-12-29 16:26:09
【问题描述】:

我正在尝试在 Go 中查找“@”字符串字符,但找不到方法。我知道如何索引像“HELLO[1]”这样会输出“E”的字符。但是我正在尝试查找找到的字符的索引号。

在 Python 中,我会采用以下方式:

x = "chars@arefun"
split = x.find("@")
chars = x[:split]
arefun = x[split+1:]

>>>print split
5
>>>print chars
chars
>>>print arefun
arefun

因此,在使用“@”分隔符时,chars 将返回“chars”,而 arefun 将返回“arefun”。我一直在努力寻找解决方案几个小时,但我似乎无法在 Golang 中找到合适的方法。

【问题讨论】:

    标签: string go character


    【解决方案1】:

    你可以使用包stringsIndex函数

    游乐场: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】:

      如果您要搜索非 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("match starts at", index);
      }
      

      搜索language.Tag structs here 以查找您要搜索的语言,如果不确定,请使用language.Und

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-14
        • 2012-05-26
        • 1970-01-01
        • 2015-05-23
        • 2020-06-08
        • 1970-01-01
        • 2022-07-22
        • 1970-01-01
        相关资源
        最近更新 更多