Saturday, July 25, 2015

toLower and toUpper Character Functions in C++ without using string.h and ctype.h

string.h and ctype.h libraries have got functions defined for converting characters from upper case to lower case and vice versa.

Sample functions below achieves in a c program following requirements :

1- convert a given character from lower case to upper case character
2- convert a given character from upper case to lower case character
3- convert a given whole string from lower case to upper case string
4- convert a given whole string from upper case to lower case string

with the following constraints :

1- All letters are English alphabet letters
2- There is no space in the input
3- Only character input is assumed


Main rule to remember when converting case for letters is :

Upper case character = Lower case character - ('a'-'A');
Lower case character = Upper case character + ('a'-'A');

Here the difference ('a'-'A') corresponds to 32.


#include <stdio.h>

char charToLower(const char& cUpper)
{
    if(cUpper>='A' && cUpper<='Z')
        return cUpper+('a'-'A');
    else
        return cUpper;
}

char charToUpper(const char& cLower)
{
    if(cLower>='a' && cLower<='z')
        return cLower-('a'-'A');
    else
        return cLower;
}

char* strToLower( char strUpper[] )
{
    int i = 0;
    while(strUpper[i] != '\0')
        i++;

    char* strLower = new char[i];
    i=0;
    while( strUpper[i] != '\0' )
    {
        if(strUpper[i]>='A' && strUpper[i]<='Z')
            strLower[i] = strUpper[i]+('a'-'A');
        i++;
    }
    return strLower;
}

char* strToUpper( char strLower[] )
{
    int i=0;
    while(strLower[i] != '\0')
        i++;

    char* strUpper = new char[i];
    i=0;
    while( strLower[i] != '\0' )
    {
        if( strLower[i]>='a' && strLower[i]<='z')
            strUpper[i] = strLower[i]-('a'-'A');
        i++;
    }
    return strUpper;
}

int main()
{
    char upperCaseChar = 'C';
    char lowerCaseChar = charToLower(upperCaseChar);
    printf("Upper Case Character : %c \n", upperCaseChar);
    printf("Lower Case Character : %c \n\n", lowerCaseChar);

    char lowerTestChar = 'f';
    char upperTestChar = charToUpper(lowerTestChar);
    printf("Lower Case Character : %c \n", lowerTestChar);
    printf("Upper Case Character : %c \n\n", upperTestChar);

    char upperCaseString[] = "TRKSH";
    char* lowerCaseString = strToLower(upperCaseString);
    printf("Upper Case String : %s \n", upperCaseString);
    printf("Lower Case String : %s \n\n", lowerCaseString);
    delete[] lowerCaseString;

    char lowerCaseTestString[] = "trksh";
    char* upperCaseTestString = strToUpper(lowerCaseTestString);
    printf("Lower Case String : %s \n", lowerCaseTestString);
    printf("Upper Case String : %s \n\n", upperCaseTestString);
    delete[] upperCaseTestString;

    return 0;
}

After running the program following terminal output displayed.


No comments:

Post a Comment