阳光VIP

少壮不努力,老大徒伤悲。平日弗用功,自到临期悔。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Compares two strings (case insensitive)

Posted on 2012-02-03 12:04  阳光VIP  阅读(140)  评论(0编辑  收藏  举报

#pragma once
#include <string>
using namespace std;

class ci_char_traits :
 public std::char_traits<char>
{
public:
 static bool eq(char c1,char c2)
 {
  return toupper(c1)==toupper(c2);
 }

 static bool lt(char c1,char c2)
 {
  return toupper(c1)<toupper(c2);
 }

 static int compare(const char* s1,const char* s2,size_t n)
 {
  return _memicmp(s1,s2,n);
 }

 static const char* find(const char* s,int n,char a)
 {
  while(n-- > 0 && toupper(*s)!=toupper(a))
  {
   ++s;
  }
  return n>0 ? s:0;
 }
};


We can use the ci_char_traits class as thus:

         basic_string<char,ci_char_traits> str1,str2;
 str1="oK";
 str2="ok";
 if(str1==str2)
 {
  cout<<"ok"<<endl;
 }
 if(str1=="ok")
 {
  cout<<"ok"<<endl;
 }
 cout<<str1.c_str()<<endl;
 return 0;