尝试反转字符串,但在反转字符串后有空格。

huangapple go评论90阅读模式
英文:

Trying to reverse strings but there are spaces after reversing the string

问题

我正在尝试编写一个字符串反转函数,用于反转给定的字符串:

func reverseString(s string) []rune

我成功地实现了这个函数,但问题是在反转后有空格。

输入:"Hello, 世界"

输出:[界 世 , o l l e H]

函数的代码如下:

func reverseString(s string) []rune {
	// 将字符串转换为 rune 切片
	sir := []rune(s)

	for i, _ := range sir {
		sir[i], sir[len(sir)-i-1] = sir[len(sir)-i-1], sir[i]
		if i >= len(sir)-i-1 {
			return sir
		}
	}
	return sir
}

由于我是 Go 语言的新手,所以可能没有出现错误的实现。

谢谢你的帮助。

英文:

I was trying to write a stringReverse function which reverses the given string:

func reverseString(s string) []rune

well, i did succeed but the problem is there are spaces after reversing it.

Input: "Hello, 世界"

Output: [界 世 , o l l e H]

code of function :

func reverseString(s string) []rune {
// sir: string in rune
sir := []rune(s)

for i, _ := range sir {
	sir[i], sir[len(sir)-i-1] = sir[len(sir)-i-1], sir[i]
	if i >= len(sir)-i-1 {
		return sir
	}
}
return sir
}

i did not do any error implementation since i am new to go.

Thanks for your help.

答案1

得分: 1

要反转字符串,你可以声明一个空字符串,然后从末尾开始逐个添加字符。以下是相同逻辑的示例代码:

package main

import "fmt"

func reverse(str string) (result string) {
    for _, v := range str {
        result = string(v) + result
    }
    return
}

func main() {
    runeStr := "Hello, 世界"
    fmt.Println(runeStr)
    runeRev := reverse(runeStr)
    fmt.Println(runeRev)
}

输出结果:

Hello, 世界
界世 ,olleH
英文:

To reverse strings,you can declare an empty string and then start appending the characters from the end, one by one.Here is a sample code for the same logic:

package main

import "fmt"

func reverse(str string) (result string) {
	for _, v := range str {
		result = string(v) + result

	}
	return
}

func main() {

	runeStr := "Hello, 世界"
	fmt.Println(runeStr)
	runeRev := reverse(runeStr)
	fmt.Println(runeRev)

}

Output:

Hello, 世界
界世 ,olleH

答案2

得分: 0

尝试将以下代码翻译为中文:

func reverseString(s string) []rune {
    // 将字符串转换为rune切片
    sir := []rune(s)
    
    for i, _ := range sir {
    
        sir[i], sir[len(sir)-i-1] = sir[len(sir)-i-1], sir[i]
        if i+1 >= len(sir)/2 {
            return sir
        }
    }
    return sir
}

请注意,这只是代码的翻译,不包括任何其他内容。

英文:

try to

func reverseString(s string) []rune {
    // sir: string in rune
    sir := []rune(s)
    
    for i, _ := range sir {
    
        sir[i], sir[len(sir)-i-1] = sir[len(sir)-i-1], sir[i]
        if i+1 >= len(sir)/2 {
            return sir
        }
    }
    return sir
}

huangapple
  • 本文由 发表于 2021年8月29日 17:55:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/68971767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定