douban5644 2014-04-03 10:46
浏览 230
已采纳

在golang的字符串数组中打印特定字节的值

I am new to go lang and I want to print the individual byte of array of string

as in below code I want to print the values 'h','e','l','l','o' once at a time but I am not able to do the same.

func main() {
    strslice := make([]string, 4, 5)
    strslice[0] = "hello"
    strslice[1] = "go"
    strslice[2] = "lang"
    strslice[3] = "whatsup"
    for i := 0; i < len(strslice[i]); i++ {
        fmt.Printf("slice is %c 
", strslice[i])
    }
}
  • 写回答

2条回答 默认 最新

  • dongtangxi1584 2014-04-03 14:12
    关注

    In Go, character literals are stored in a string as a variable-width sequence of UTF-8 encoded bytes. The ASCII code points (0x00..0x7F) occupy one byte. Other code points occupy two to four bytes. To print code points (characters) separately,

    package main
    
    import "fmt"
    
    func main() {
        strslice := make([]string, 5, 5)
        strslice[0] = "hello"
        strslice[1] = "go"
        strslice[2] = "lang"
        strslice[3] = "whatsup"
        strslice[4] = "Hello, 世界"
        for _, s := range strslice {
            for _, c := range s {
                fmt.Printf("%c ", c)
            }
            fmt.Printf("
    ")
        }
    }
    

    Output:

    h e l l o 
    g o 
    l a n g 
    w h a t s u p 
    H e l l o ,   世 界 
    

    Here's an illustration of the difference between UTF-8 encoded bytes and characters,

    package main
    
    import "fmt"
    
    func main() {
        str := "Hello, 世界"
        fmt.Println("Bytes:")
        for i := 0; i < len(str); i++ {
            fmt.Printf("'%c' ", str[i])
        }
        fmt.Printf("
    ")
        fmt.Println("Characters:")
        for _, c := range str {
            fmt.Printf("'%c' ", c)
        }
        fmt.Printf("
    ")
    }
    

    Output:

    Bytes:
    'H' 'e' 'l' 'l' 'o' ',' ' ' 'ä' '¸' '' 'ç' '' '' 
    Characters:
    'H' 'e' 'l' 'l' 'o' ',' ' ' '世' '界' 
    

    References:

    Unicode UTF-8 FAQ

    For statements, The Go Programming Language Specification

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 flask项目,怎么使用AJAX传数据库数据到echarts图表的data里,实现异步加载数据。
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题