Thiago R. Adams website

Home Blog Code-Blog Twitter Downloads Links / Books About

Websites

cmp_nocase for standard strings


int cmp_nocase(const std::string& s, const std::string& s2)
{
  std::string::const_iterator p  = s.begin();
  std::string::const_iterator p2 = s2.begin();

  while (p != s.end() && p2 != s2.end())
  {
    if (toupper(*p) != toupper(*p2))
    {
      return (toupper(*p) < toupper(*p2)) ? -1 : 1;
    }
    ++p;
    ++p2;
  }
  return (s2.size()==s.size()) ? 0 : (s.size() < s2.size()) ? -1 : 1;
}

//From book: The C++ Programming Language
See also find_replace



int cmp_nocase(const std::wstring& s, const std::wstring& s2)
{
  std::wstring::const_iterator p  = s.begin();
  std::wstring::const_iterator p2 = s2.begin();

  while (p != s.end() && p2 != s2.end())
  {
    if (toupper(*p) != toupper(*p2))
    {
      return (toupper(*p) < toupper(*p2)) ? -1 : 1;
    }
    ++p;
    ++p2;
  }
  return (s2.size()==s.size()) ? 0 : (s.size() < s2.size()) ? -1 : 1;
}



template<class CharType>
int cmp_nocase(const std::basic_string<CharType>& s, const std::basic_string<CharType>& s2)
{
  std::basic_string<CharType>::const_iterator p  = s.begin();
  std::basic_string<CharType>::const_iterator p2 = s2.begin();

  while (p != s.end() && p2 != s2.end())
  {
    if (toupper(*p) != toupper(*p2))
    {
      return (toupper(*p) < toupper(*p2)) ? -1 : 1;
    }
    ++p;
    ++p2;
  }
  return (s2.size()==s.size()) ? 0 : (s.size() < s2.size()) ? -1 : 1;
}

Want to see more? Go to the CodeBlog section.

About the author: I am Thiago Adams. I work as a professional C++ software engineer. I have created this website to share ideas and source code with other people with similar interests.
I would like to hear from you comments, critics, questions and suggestions about this topic or any other part of this website. Email: thiago.adams at gmail dot com