The general solution to interpreting a char as a string is string("HELLO"[1])
.
Rich's solution also works, of course.
Another Solution to isolate a character in a string
package main
import "fmt"
func main() {
var word string = "ZbjTS"
// P R I N T
fmt.Println(word)
yo := string([]rune(word)[0])
fmt.Println(yo)
//I N D E X
x :=0
for x < len(word){
yo := string([]rune(word)[x])
fmt.Println(yo)
x+=1
}
}
for string arrays also:
fmt.Println(string([]rune(sArray[0])[0]))
// = commented line
Try this to get the charecters by their index
package main
import (
"fmt"
"strings"
)
func main() {
str := strings.Split("HELLO","")
fmt.Print(str[1])
}
How about this?
fmt.Printf("%c","HELLO"[1])
As Peter points out, to allow for more than just ASCII:
fmt.Printf("%c", []rune("HELLO")[1])
Can be done via slicing too
package main
import "fmt"
func main() {
fmt.Print("HELLO"[1:2])
}
NOTE: This solution only works for ASCII characters.
String characters are runes, so to print them, you have to turn them back into String.
fmt.Print(string("HELLO"[1]))
Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x)
. The %c
format specification works for any integer type.
You can also try typecasting it with string.
package main
import "fmt"
func main() {
fmt.Println(string("Hello"[1]))
}
Source: Stackoverflow.com