<p>I want to take the word "Computer" and produce 8 numbers representing the ascii integers. I just started learning golang and only know the very basics (functions, arrays, loops) so the more elementary the better. </p>
<hr/>**评论:**<br/><br/>planet12: <pre><p>You can loop over the characters using "range", eg.</p>
<pre><code>s := "Computer"
for _, c := range s {
fmt.Printf("c = %d (%c)\n", c, c)
}
</code></pre>
<p>Output:</p>
<pre><code>c = 67 (C)
c = 111 (o)
c = 109 (m)
c = 112 (p)
c = 117 (u)
c = 116 (t)
c = 101 (e)
c = 113 (r)
</code></pre>
<p>Take a look at <a href="https://blog.golang.org/strings" rel="nofollow">https://blog.golang.org/strings</a></p></pre>chronokitsune3233: <pre><p>Another way to do it is to convert to <code>[]byte</code> (a slice of bytes):</p>
<pre><code>func printBytes(s string) {
sbytes := []byte(s)
// You can also replace this with something like fmt.Printf("% x\n", sbytes)
// if you want different output.
fmt.Println(sbytes)
}
</code></pre>
<p>If you want to print each byte individually along with the character it corresponds to, you might do something like this:</p>
<pre><code>func printBytes(s string) {
for i := 0; i < len(s); i++ {
fmt.Printf("Byte %3d: %3d %c\n", i, s[i], s[i])
}
}
</code></pre>
<p>This differs from <code>for ... range s</code> subtly since a <code>range</code> over a string results in the runes of the string being looped over. For ASCII, it doesn't matter, but for all other characters (e.g. characters like <code>á</code>), <a href="https://play.golang.org/p/BGiufc52Jj" rel="nofollow">it matters</a>. Of course, if you have bytes in the string that don't form a valid UTF-8 sequence, the rune received for each "bad" byte would be the value of <a href="https://golang.org/pkg/unicode/#pkg-constants" rel="nofollow"><code>unicode.ReplacementChar</code></a>. You can find out more by reading <a href="https://blog.golang.org/strings" rel="nofollow">Strings, bytes, runes and characters in Go</a> as suggested in another comment.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传