Golang : Break string into a slice of characters example
Problem:
You want to convert a string into a slice/array of individual characters. It is similar to breaking down a string into slice/array example with strings.Fields()
function. but instead of words, you want to break into single characters. How to do that?
Solution:
Use for loop range to break the string into characters and then use text/Scanner.TokenString()
function to return a printable string for a token or Unicode character.
Here you go!
package main
import (
"fmt"
"text/scanner"
)
func breakToCharSlice(str string) []string {
tokens := []rune(str)
var result []string
for _, char := range tokens {
result = append(result, scanner.TokenString(char))
}
return result
}
func main() {
str := "Ace of Hearts"
temp := breakToCharSlice(str)
for k, v := range temp {
fmt.Println(k, v)
}
unicodestr := "α제ちمرحباהיי"
temp = breakToCharSlice(unicodestr)
for k, v := range temp {
fmt.Println(k, v)
}
}
Output:
0 "A"
1 "c"
2 "e"
3 " "
4 "o"
5 "f"
6 " "
7 "H"
8 "e"
9 "a"
10 "r"
11 "t"
12 "s"
0 "α"
1 "제"
2 "ち"
3 "م"
4 "ر"
5 "ح"
6 "ب"
7 "ا"
8 "ה"
9 "י"
10 "י"
See also : Golang : Convert string to array/slice
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.9k Golang : Use modern ciphers only in secure connection
+7k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+16.8k Golang : Find file size(disk usage) with filepath.Walk
+4.5k Golang : How to pass data between controllers with JSON Web Token
+5.2k Golang : Reclaim memory occupied by make() example
+13.8k Golang : Google Drive API upload and rename example
+5.1k Unix/Linux/MacOSx : How to remove an environment variable ?
+18.5k Golang : convert int to string
+19.9k Golang : Count number of digits from given integer value
+29k Golang : JQuery AJAX post data to server and send data back to client example
+15.4k Golang : Get digits from integer before and after given position example
+18.4k Golang : Implement getters and setters