去除句子末尾的空格。

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

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, &quot; &quot;)` to remove spaces on both sides.


If you only need at the end, then use `text = strings.TrimRight(text, &quot; &quot;)`


</details>



huangapple
  • 本文由 发表于 2021年12月14日 08:04:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/70342307.html
匿名

发表评论

匿名网友

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

确定