Home > database >  Remove whitespace at end of sentence
Remove whitespace at end of sentence

Time:12-14

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)

}

CodePudding user response:

Use text = strings.Trim(text, " ") to remove spaces on both sides.

If you only need at the end, then use text = strings.TrimRight(text, " ")

CodePudding user response:

Use strings.TrimSpace which trims all whitespace from both ends.

text = strings.TrimSpace(text)

package strings

func TrimSpace(s string) string

TrimSpace returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.

  •  Tags:  
  • go
  • Related