Monday, March 7, 2011

Code: Make first character of string to upper case


Here the problem is just simple, we have to make uppercase to the first character of every input string. 


First Method: In this method we are going to consider that the string is having only ASCII characters. Then we will check first if the character fall between a to z, if yes then we will convert it to upper case by just adding the difference as shown below.

void MakeFirstCharUpper(char* pchInputString)
{
int aToInt = (int)'a';
int zToInt = (int)'z';
int AtoInt = (int)'A';


if(pchInputString == NULL)
return ;


int firstChar = (int)*pchInputString;
if(firstChar  <= zToInt && firstChar  >= aToInt )
{
*pchInputString = (char)(AtoInt + (firstChar  - aToInt));
}
}


Second Method: 
This will require when your string contains UNICODE characters. Here we will make copy of the original string, we will make that string to upper case, then we will only copy the first character of upper case string to original string.



void MakeFirstCharUpperUNICODEVersion(char* pchInputString)
{
if( NULL == pchInputString)
return;


if(strlen(pchInputString) == 1)
{
pchInputString = strupr(pchInputString);
return;
}


char* strPartI = new char(strlen(pchInputString));
strncpy(strPartI, pchInputString, strlen(pchInputString));


strPartI = strupr(strPartI);


*pchInputString = *strPartI;
}

No comments:

Post a Comment