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

时间:2014-11-25 18:18:55

标签: go

我必须为我的学校做一个加密项目,我为这个项目选择了Go!

我读了文档,但我只读了C,所以现在对我来说有点困难。

首先,我需要收集程序参数,我做了。我将所有参数存储在字符串变量中,如:

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

现在,我需要将ASCII数存储在int数组中,例如,在C中,我会做类似的事情:

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

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

那么我怎么能在Go中做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:2)

我的猜测是你想要这样的东西:

package main

import (
    "fmt"
    "strings"
)

// transform transforms ASCII letters to numbers.
// Letters in the English (basic Latin) alphabet, both upper and lower case,
// are represented by a number between one and twenty-six. All other characters,
// including space, are represented by the number zero.
func transform(s string) []int {
    n := make([]int, 0, len(s))
    other := 'a' - 1
    for _, r := range strings.ToLower(s) {
        if 'a' > r || r > 'z' {
            r = other
        }
        n = append(n, int(r-other))
    }
    return n
}

func main() {
    s := "Hi Stack OverFlow"
    fmt.Println(s)
    n := transform(s)
    fmt.Println(n)
}

输出:

Hi Stack OverFlow
[8 9 0 19 20 1 3 11 0 15 22 5 18 6 12 15 23]

选择A Tour of Go,看看你是否能理解该计划的作用。

答案 1 :(得分:2)

这是一个与其他答案类似的示例,但避免导入其他包。

创建一个int切片,其长度等于string的长度。然后遍历字符串以将每个字符提取为int,并将其分配给int切片中的相应索引。这是代码(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
}

上述计划的输出是:

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

上面的StringToInts功能可以做你想要的。虽然它返回slice的{​​{1}}(不是数组),但它应该满足您的用例。