Slice unicode/ascii strings in golang?

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

Slice unicode/ascii strings in golang?

问题

我需要在Go中切割一个字符串。可能的值可以包含拉丁字符和/或阿拉伯/中文字符。在下面的示例中,对于阿拉伯字符串字母的切片注释[:1]返回了一个非预期的值/字符。

    package main
    
    import "fmt"
    
    func main() {
        a := "a"
        fmt.Println(a[:1]) // 正常工作
        
        b := "ذ"
        fmt.Println(b[:1]) // 不正常工作
        fmt.Println(b[:2]) // 正常工作
    
        fmt.Println(len(a) == len(b)) // false
    }

http://play.golang.org/p/R-JxaxbfNL

英文:

I need to slice a string in Go. Possible values can contain Latin chars and/or Arabic/Chinese chars. In the following example, the slice annotation [:1] for the Arabic string alphabet is returning a non-expected value/character.

    package main
    
    import "fmt"
    
    func main() {
    	a := "a"
    	fmt.Println(a[:1]) // works
    	
    	b := "ذ"
    	fmt.Println(b[:1]) // does not work
    	fmt.Println(b[:2]) // works
    
    	fmt.Println(len(a) == len(b)) // false
    }

http://play.golang.org/p/R-JxaxbfNL

答案1

得分: 30

首先,你应该真正阅读一下关于Go语言中的字符串、字节和符文的内容。

以下是你可以实现你想要的效果的方法:<kbd>Go playground</kbd>(我无法正确粘贴阿拉伯符号,但如果中文可以工作,阿拉伯语也应该可以)。

    s := &quot;abcdefghijklmnop&quot; 
    fmt.Println(s[2:9]) 

    s = &quot;维基百科:关于中文维基百科&quot; 
    fmt.Println(string([]rune(s)[2:9]))

输出结果为:

cdefghi
百科:关于中文
英文:

First of all, you should really read about strings, bytes and runes in Go.

And here is how you can achieve what you want: <kbd>Go playground</kbd> (I was not able to properly paste arabic symbols, but if Chinese works, arabic should work too).

    s := &quot;abcdefghijklmnop&quot; 
    fmt.Println(s[2:9]) 

    s = &quot;维基百科:关于中文维基百科&quot; 
    fmt.Println(string([]rune(s)[2:9]))

The output is:

cdefghi
百科:关于中文

答案2

得分: 0

你可以使用utf8string包:

package main
import "golang.org/x/exp/utf8string"

func main() {
   a := utf8string.NewString("🎈🎄🎀🎂🀃")
   // 示例 1
   r := a.At(1)
   // 示例 2
   s := a.Slice(1, 3)
   // 示例 3
   n := a.RuneCount()
   // 打印
   println(r == '🎄', s == "🎄🎀", n == 5)
}

https://pkg.go.dev/golang.org/x/exp/utf8string

英文:

You can use the utf8string package:

package main
import &quot;golang.org/x/exp/utf8string&quot;

func main() {
   a := utf8string.NewString(&quot;&#127880;&#127876;&#127872;&#127906;&#128083;&quot;)
   // example 1
   r := a.At(1)
   // example 2
   s := a.Slice(1, 3)
   // example 3
   n := a.RuneCount()
   // print
   println(r == &#39;&#127876;&#39;, s == &quot;&#127876;&#127872;&quot;, n == 5)
}

https://pkg.go.dev/golang.org/x/exp/utf8string

huangapple
  • 本文由 发表于 2015年7月15日 06:17:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/31418376.html
匿名

发表评论

匿名网友

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

确定