Sunday, November 22, 2009

Convert string to all caps in C

/*Sample code to convert to ALL CAPS a given string. */

#include
<stdio.h>
#include<string.h>

main()
{

int len =0;
int i =0;

char *str="quick BroWn Fox juMP ovEr the HeAd";
char *up_str;

len=strlen(str);
/*strlen does not include '\0' in the count so we allocate space for it*/
up_str=malloc((len+1)*sizeof(char));

printf("\nThis is the sample string: %s\n", str);
printf("\nThe length: %d",len);

for(i=0;i<=len;i++){ *(up_str+i)= toupper(*(str+i));
/* In C, *(array+1) == array[1] */
if(i==len){
*(up_str+i)='\0';
}
}

printf("\nThe upper string: %s\n", up_str);
free(up_str);
system("PAUSE");
}

No comments: