In Go, you can remove leading and trailing whitespace using strings.TrimSpace():
// strings.TrimSpace() removes leading and trailing whitespace (spaces, tabs, newlines)
s := " hello "
result := strings.TrimSpace(s)
// result == "hello"
Here is how a simple trim function for spaces could work:
func trimSpace(s string) string {
start, end := 0, len(s)-1
for start <= end && s[start] == ' ' {
start++
}
for end >= start && s[end] == ' ' {
end--
}
return s[start : end+1]
}
Assignment
Follow the Coding Tutorial and use strings.TrimSpace() to strip whitespace from s!
Hint
Use strings.TrimSpace(s) and assign the result to result.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
