Golang is a programming language launched by Google. Its design goal is to improve the efficiency and maintainability of software development. In Golang, characters and strings are two different data types, but we often encounter the need to convert a string into a character array. This article will introduce how to convert characters to arrays in Golang.
In Golang, the concepts of characters and strings are relatively clear. A character is a Unicode code point and occupies 4 bytes; while a string is a sequence of multiple characters, encoded using UTF-8, and each character occupies 1-4 bytes. Therefore, when we need to convert a string into a character array, we need to consider the following questions:
Let’s explain them one by one below.
In Golang, the data type of character is rune, which is an alias of int32 type. Therefore, when we define a character array, its element type should be rune.
var arr []rune
In Golang, you can use the len() function to get the length of a string, but the length of the string is not equal to it The number of characters contained. Because a Unicode character may consist of multiple bytes, the length of a string is often not the same as the number of characters it contains. In order to correctly convert a string into an array of characters, we should use the functions in the unicode/utf8 package to count the number of characters the string contains.
import "unicode/utf8" func countChars(s string) int { return utf8.RuneCountInString(s) } length := countChars("Hello, world!") arr := make([]rune, length)
Golang provides two functions to convert a string into a character array: []rune() and []byte(). Among them, []rune() converts a string into an array of rune type, each character occupies 4 bytes; []byte() converts a string into an array of byte type, each character occupies 1 bytes, but garbled characters may appear.
s := "Hello, 世界" arr := []rune(s) // 将字符串s转换成rune类型的数组
The complete code is as follows:
package main import ( "fmt" "unicode/utf8" ) func countChars(s string) int { return utf8.RuneCountInString(s) } func main() { s := "Hello, 世界" length := countChars(s) arr := make([]rune, length) for i, c := range s { arr[i] = c } fmt.Println(arr) }
The running results are as follows:
[72 101 108 108 111 44 32 19990 30028]
Through the introduction of this article, we understand how to convert a string into a character array in Golang . This is helpful for working with text data and implementing algorithms on strings.
The above is the detailed content of golang character to array. For more information, please follow other related articles on the PHP Chinese website!