I am looking for specific file types from a directory listing and use HasSuffix to do the comparision looking for a few specific file types. I would like to make this comparison case insensitive.
Is there a way to add EqualFold or another case insensitive comparison to the HasSuffix function?
You could just use
if strings.HasSuffix(strings.ToLower(s), "suffix") {
// do something
}
You can also write your own wrapper function:
func hasSuffix(s, suffix string, caseSensitive bool) bool {
if caseSensitive {
return strings.HasSuffix(s, suffix)
}
return strings.HasSuffix(strings.ToLower(s), suffix)
}
For file names or paths you can use (see answer of PeterSO):
if strings.ToLower(filepath.Ext(s)) == ".fileending" {
// do something
}
"I am looking for specific file types from a directory listing. I would like to make this comparison case insensitive."
For example,
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func hasExts(path string, exts []string) bool {
pathExt := strings.ToLower(filepath.Ext(path))
for _, ext := range exts {
if pathExt == strings.ToLower(ext) {
return true
}
}
return false
}
func main() {
dir := `./`
files, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
sourceExts := []string{".go", ".Py", ".c", ".cpp"}
for _, fi := range files {
if hasExts(fi.Name(), sourceExts) {
fmt.Println(fi.Name())
}
}
}
Output:
t.c
t.go
t.py
t1.go
t1.py
t2.go
For a special form of strings.HasSuffix
start by copying the code from the strings
package.
func HasSuffix(s, suffix string) bool {
return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}
Then modify it to suit your purpose. For example,
func hasSuffix(s, suffix string) bool {
return len(s) >= len(suffix) &&
strings.ToLower(s[len(s)-len(suffix):]) == strings.ToLower(suffix)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With