英文:
Remove whitespace at end of sentence
问题
这里是一些背景信息。
用户输入 test hello world
(包括空白空格)
我需要将这个输入改为 test hello world
这是一些代码,如果我输入带有空格的前面的字符串,它只会删除一个空格,而在 trimsuffix 中添加多个空格将创建单个用例,例如只有 10 个空格。
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
text := scanner.Text()
text = strings.TrimSuffix(text, " ")
fmt.Printf("%s", text)
}
英文:
Here's some context.
The user enters test hello world
(including the empty whitespace)
I need this input to be changed into test hello world
Heres some code, if I enter the previous string with the whitespace, it only removes 1 space and adding more than one to the trimsuffix will create singular use cases such as only 10 spaces.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
text := scanner.Text()
text = strings.TrimSuffix(text, " ")
fmt.Printf("%s", text)
}
</details>
# 答案1
**得分**: 2
使用`text = strings.Trim(text, " ")`来去除两侧的空格。
如果你只需要去除末尾的空格,那么使用`text = strings.TrimRight(text, " ")`。
<details>
<summary>英文:</summary>
Use `text = strings.Trim(text, " ")` to remove spaces on both sides.
If you only need at the end, then use `text = strings.TrimRight(text, " ")`
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论