Logo

Programming-Idioms

  • Go
  • Rust

Idiom #133 Case-insensitive string contains

Set boolean ok to true if string word is contained in string s as a substring, even if the case doesn't match, or to false otherwise.

let ok = s.to_ascii_lowercase().contains(&word.to_ascii_lowercase());
extern crate regex;
use regex::Regex;
let re = Regex::new(&format!("(?i){}", regex::escape(word))).unwrap();
let ok = re.is_match(&s);
extern crate regex;
use regex::RegexBuilder;
let re =
    RegexBuilder::new(&regex::escape(word))
    .case_insensitive(true)
    .build().unwrap();

let ok = re.is_match(s);
import "strings"
lowerS, lowerWord := strings.ToLower(s), strings.ToLower(word)
ok := strings.Contains(lowerS, lowerWord)

Package strings has no case-insensitive version of Contains, so we have to convert to lowercase (or uppercase) first.
#include <algorithm>
#include <cctype>
auto ok = std::search(std::begin(s), std::end(s), std::begin(word), std::end(word),
    [](auto c, auto d){
        return std::tolower(c) == std::tolower(d);
    }
) != std::end(s);

New implementation...