duanmanpi9358 2015-07-14 22:17
浏览 73
已采纳

在Go中切片字符串:如何切片阿拉伯(或其他unicode)字符串?

I need to slice a string in Go. Sometimes I have latin chars, otherwise I have arabic chars, but [:1] for arabic returns a different value.

package main

import "fmt"

func main() {
    a := "a"
    fmt.Println(a[:1]) // work

    b := "ذ"
    fmt.Println(b[:1]) // not work
    fmt.Println(b[:2]) // work

    fmt.Println(len(a) == len(b)) // false
}

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

  • 写回答

1条回答 默认 最新

  • dpbtbcz6650 2015-07-14 22:41
    关注

    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 := "abcdefghijklmnop" 
        fmt.Println(s[2:9]) 
    
        s = "维基百科:关于中文维基百科" 
        fmt.Println(string([]rune(s)[2:9]))
    

    The output is:

    cdefghi
    百科:关于中文
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题