Case insensitive string search in golang

后端 未结 4 1091
清歌不尽
清歌不尽 2020-12-24 13:09

How do I search through a file for a word in a case insensitive manner?

For example

If I\'m searching for UpdaTe in

4条回答
  •  伪装坚强ぢ
    2020-12-24 13:42

    Presumably the important part of your question is the search, not the part about reading from a file, so I'll just answer that part.

    Probably the simplest way to do this is to convert both strings (the one you're searching through and the one that you're searching for) to all upper case or all lower case, and then search. For example:

    func CaseInsensitiveContains(s, substr string) bool {
        s, substr = strings.ToUpper(s), strings.ToUpper(substr)
        return strings.Contains(s, substr)
    }
    

    You can see it in action here.

提交回复
热议问题