Reputation: 703
I want to get the string length, here my code:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Text to send: ")
text, _ := reader.ReadString('\n')
fmt.Print(strconv.Itoa(len(text)))
}
For input: aaa
The output is 5
but should be 3
.
I know I can just subtract -2 from the result but I want "cleaner" way
Upvotes: 1
Views: 948
Reputation: 24234
You need to remove whitespaces from your input:
import (
"fmt"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Text to send: ")
text, _ := reader.ReadString('\n')
newText := strings.TrimSpace(text)
fmt.Print(strconv.Itoa(len(newText)))
}
Upvotes: 0