C program to convert uppercase to lowercase and vice versa
In this program, you will learn how you can convert strings from uppercase to lowercase and lowercase to uppercase. In C language every character represents an integer value known as ASCII. ASCII value of small (a-z) are (97-122) and capital (A-Z) are (65-90)
small capital a 97 A 65 b 98 B 66 c 99 C 67 . . . . . . z 122 Z 90
Convert string case program in c
#include<stdio.h>
void main()
{
char str[20];
int i;
printf("\n enter a string:");
gets(str);
for(i=0;str[i]!='\0';i++)
{
//it will convert lowercase to uppercase
if(str[i]>=97 && str[i]<=122)
{
str[i]=str[i]-32;
}
//it will convert uppercase to lowercase
else if(str[i]>=65 && str[i]<=90)
{
str[i]=str[i]+32;
}
}
printf(" %s",str);
}
output
enter a string:WELcome TO MY Website welCOME to my wEBSITE
Convert string case using pointer
#include<stdio.h>
#include<conio.h>
int main()
{
char a[20],*p;
int c=0,i;
p=a;
printf("\nenter a string:");
gets(a);
for(i=0;*(p+i)!='\0';i++)
{
if(*(p+i)>='a' && *(p+i)<='z')
*(p+i)=*(p+i)-32;
else if(*(p+i)>='A' && *(p+i)<='Z')
*(p+i)=*(p+i)+32;
}
printf("string:%s",p);
return 0;
}
output
enter a string:WELcome TO MY Website welCOME to my wEBSITE
explanation of string case conversion
- input string from the user, and store it some variable say
str - run the loop from 0 till end of string
- When you want to change from lowercase to uppercase, you have to substract the ASCII value of lowercase letters to 32.why subtracting it with 32 because diffrence of
a-A=32 - For example
a-32=A i.e 97-32=65 - When you want to change from uppercase to lowercase, you have to add the ASCII value of uppercase letters to 32.
- For example
A+32=a i.e 65+32=97 - 65 is ASCII value of capital A and 97 is ASCII value of small