doukuiqian5345 2014-11-25 18:18
浏览 174
已采纳

如何像C中那样将字符串转换为ASCII字符串?

I have to do a cryptography project for my school and I choose Go for this project !

I read the doc but I only C, so it's kinda hard for me right now.

First , I needed to collect the program arguments, I did it. I stockd all arguments in a string variable like :

var text, base string = os.Args[1], os. Args[6]

Now , i need to store the ASCII number in a array of int , for exemple , in C I would done something like that :

int     arr[18];
char    str[18] = "Hi Stack OverFlow";

arr[i] = str[i] - 96;

So how could I do that in Go?

Thanks !

  • 写回答

2条回答 默认 最新

  • dongmu2517 2014-11-26 00:32
    关注

    Here's an example that is similar to the other answer but avoids importing additional packages.

    Create a slice of int with the length equal to the string's length. Then iterate over the string to extract each character as int and assign it to the corresponding index in the int slice. Here's code (also on the Go Playground):

    package main
    
    import "fmt"
    
    func main() {
        s := "Hi Stack OverFlow"
        fmt.Println(StringToInts(s))
    }
    
    // makes a slice of int and stores each char from string
    // as int in the slice
    func StringToInts(s string) (intSlice []int) {
        intSlice = make([]int, len(s))
        for i, _ := range s {
            intSlice[i] = int(s[i])
        }
        return
    }
    

    Output of the above program is:

    [72 105 32 83 116 97 99 107 32 79 118 101 114 70 108 111 119]
    

    The StringToInts function in the above should do what you want. Though it returns a slice (not an array) of int, it should satisfy your usecase.

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

报告相同问题?

悬赏问题

  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路