- Check if a string starts with a substring
- Check if a string ends with a substring
- Calculate the maximum string length in a slice of strings
- Comparing strings case insensitive
Check if a string starts with a substring
package main
import (
"strings"
)
func main() {
strings.HasPrefix("flavio", "fla") // true
}
Check if a string ends with a substring
package main
import (
"strings"
)
func main() {
strings.HasSuffix("flavio", "vio") // true
}
Calculate the maximum string length in a slice of strings
// calculatemaxwidth given a slice of strings calculates the maximum
// length
func calculatemaxwidth(lines []string) int {
w := 0
for _, l := range lines {
len := utf8.RuneCountInString(l)
if len > w {
w = len
}
}
return w
}
Comparing strings case insensitive
Instead of running ToUpper()
or ToLower()
from the strings
or bytes
packages, use strings.EqualFold()
or bytes.EqualFold()
, because they are guaranteed to work across all languages.
package main
import (
"bytes"
"fmt"
)
func main() {
fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
}