如何在GO中操纵字符串以反转它们? [英] How to manipulate strings in GO to reverse them?
问题描述
我正在尝试反转一个字符串,但是在处理字符时遇到了麻烦.与C不同,GO将字符串视为字节的向量,而不是字符,在这里称为符文.我尝试进行一些类型转换来完成分配,但到目前为止我还做不到.
I'm trying to invert a string in go but I'm having trouble handling the characters. Unlike C, GO treats strings as vectors of bytes, rather than characters, which are called runes here. I tried to do some type conversions to do the assignments, but so far I could not.
这里的想法是生成5个具有100、200、300、400和500大小的随机字符的字符串,然后反转它们的字符.我可以轻松地使用C,但是在GO语言中,该语言返回了一个错误,指出无法执行分配.
The idea here is to generate 5 strings with random characters of sizes 100, 200, 300, 400 and 500 and then invert their characters. I was able to make C work with ease, but in GO, the language returns an error saying that it is not possible to perform the assignment.
func inverte() {
var c = "A"
var strs, aux string
rand.Seed(time.Now().UnixNano())
// Gera 5 vetores de 100, 200, 300, 400, e 500 caracteres
for i := 1; i < 6; i++ {
strs = randomString(i * 100)
fmt.Print(strs)
for i2, j := 0, len(strs); i2 < j; i2, j = i+1, j-1 {
aux = strs[i2]
strs[i2] = strs[j]
strs[j] = aux
}
}
}
推荐答案
正确识别后,转到字符串是不可变的,因此您无法在给定的索引处分配符文/字符值.
As you correctly identified, go strings are immutable, so you cannot assign to rune/character values at given indices.
与其代替就地反转字符串,还必须在字符串中创建一个符文副本,然后反转它们,然后返回结果字符串.
Instead of reversing the string in-place one must create a copy of the runes in the string and reverse those instead, and then return the resulting string.
例如(进入操场):
func reverse(s string) string {
rs := []rune(s)
for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
rs[i], rs[j] = rs[j], rs[i]
}
return string(rs)
}
func main() {
fmt.Println(reverse("Hello, World!"))
// !dlroW ,olleH
fmt.Println(reverse("Hello, 世界!"))
// !界世 ,olleH
}
由于Unicode的复杂性,这种方法存在一些问题(例如组合变音符号),但这会让您入门.
There are problems with this approach due to the intricacies of Unicode (e.g. combining diacritical marks) but this will get you started.
这篇关于如何在GO中操纵字符串以反转它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!