Monday, November 30, 2015

Case Insensitive String Compare in C++

Sometimes you want to compare or read a string in 'case-sensitive' mode (i.e. whether a letter is capital or lowercase matters), while at other times you want to compare or read a string without worrying about the case  (i.e. case insensitive). Passwords, for instance, would be best compared/read in case-sensitive mode...while some AI interfaces that want to read what the user is inputing would be best read in case-insensitive mode.

So on to the code. This is a simple way of converting text input to all upper-case, thereby being able to read/compare the input without having to worry about case sensitivity...

#include <iostream>
using namespace std;

void tocaps(char *);
int main()
{
  char input_string[200];
  cout << "Enter a string :"; cin >> input_string;
  tocaps(input_string);
  cout << "After upper case conversion :" <<endl << input_string;
  return 0;
}

void tocaps(char *a)
{
  int i=0;
  while(*(a+i)!='\0')
  {
    if(*(a+i)>=97 && *(a+i)<=122) (*(a+i))-=32;
    i++;
  }
}

No comments:

Post a Comment