Go pakacge ASCII

Package main works perfectly fine, but when I try to use package ascii I get: cannot run non-main package.

I need ascii pagacke. I need to get the entire ascii table and run it through IterateOverASCIIStringLiteral(sl string) and then print it in fmt.Printf"%X %c %b/n".

Do I have to write the entire ascii table manually or is there a way to slice through it and then itterateOverASCIIStringLiteral? I’m new to go and this is driving me crazy :slight_smile:

Here is a simple way to print the ASCII table:

package main

import (
	"fmt"
)

func main() {
	for i := 0; i <= 255; i++ {
		fmt.Printf("%3[1]d %2[1]X %8[1]q %8[1]b\n", i)
	}
}

Playground link

The [1] index instructs all verbs to use the i variable. I added the %d verb to print the decimal value. I also replaced the %c verb with %q to safely escape the characters. The decimal numbers on the verbs specify the width in units of Unicode code points. You can read more about these here.

To get a better understanding of how strings work, please read Strings, bytes, runes and characters in Go.

1 Like

Oh wow for real. That’s a lot simpler then I tought. Thanks a lot. I have manually typed inn all the ascii. For I need to use this.
“func IterateOverASCIIStringLiteral(sl string)” But I can’t find out where to learn how to use it. When I write
func IterateOverASCIIStringLiteral(sl string)
a := ascii
for i := 0; i < len(A); i++ {
fmt.Printf"%X %c %b/n", a[i], a[i], a[i])
}
The sl becomes an unresolved refrence. Any ideas?

How about this:

package main

import (
	"fmt"
)

func main() {
	IterateOverASCIIStringLiteral("hello")
}

func IterateOverASCIIStringLiteral(s string) {
	for _, r := range s {
		fmt.Printf("%X %c %b\n", r, r, r)
	}
}

A for range loop, decodes one UTF-8-encoded rune on each iteration.

Please note that the Go source code is UTF-8 so writing ASCII in the function name is not accurate.

Thanks man. I finally understand more of golang and a little bit of coding. I managed to make all mye functions and run them in main. The output is perfect. Now I want to write a test. to see if the string I have written only contains ascii values.

Is this ok?
func isASCII(s string) bool {
for _, c := range s {
if c > 127 {
return false
}
}
return true
}

1 Like

hmm, but I need it in a test file. So I guess not :stuck_out_tongue: I’ll do some more reading.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.