Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive string::find

Tags:

c++

Is there exist a case-insensitive find() method for std::string?

like image 384
user4344 Avatar asked Feb 09 '11 10:02

user4344


People also ask

Is find case-sensitive in C++?

Yes. C++ is case sensitive. Because the code are then compiled and each character has a different code.

Is find python case-sensitive?

The find() method performs case-sensitive search. It returns -1 if a substring is not found.

How do you ignore a case in C++?

The strcasecmp() function performs a byte-by-byte comparison of the strings s1 and s2, ignoring the case of the characters. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.


3 Answers

You could upper-case both strings and use the regular find. (Note: this approach may not be correct if you have Unicode string.)

In Boost there's also ifind_first for case-insensitive search. (note that it returns a range instead of a size_t).

#include <string>
#include <boost/algorithm/string/find.hpp>
#include <cstdio>
#include <cctype>

std::string upperCase(std::string input) {
  for (std::string::iterator it = input.begin(); it != input.end(); ++ it)
    *it = toupper(*it);
  return input;
}

int main () {
  std::string foo = "1 FoO 2 foo";
  std::string target = "foo";

  printf("string.find: %zu\n", foo.find(target));

  printf("string.find w/ upperCase: %zu\n", upperCase(foo).find(upperCase(target)));

  printf("ifind_first: %zu\n", boost::algorithm::ifind_first(foo, target).begin() - foo.begin());

  return 0;
}
like image 173
kennytm Avatar answered Nov 01 '22 17:11

kennytm


this is what I would have suggested, (the same as @programmersbook)

#include <iostream>
#include <algorithm>
#include <string>

bool lower_test (char l, char r) {
  return (std::tolower(l) == std::tolower(r));
}

int main()
{
  std::string text("foo BaR");
  std::string search("bar");

  std::string::iterator fpos = std::search(text.begin(), text.end(), search.begin(), search.end(), lower_test);
  if (fpos != text.end())
    std::cout << "found at: " << std::distance(text.begin(), fpos) << std::endl;
  return 0;
}
like image 43
Nim Avatar answered Nov 01 '22 16:11

Nim


Before doing anything fancy, have a look at

http://www.gotw.ca/gotw/029.htm

and see if using a custom character traits class is not what you want.

like image 3
Alexandre C. Avatar answered Nov 01 '22 16:11

Alexandre C.