Home Strings Write a program to change the case of each character in a string

Write a program to change the case of each character in a string

by nikoo28
1 comment 2 minutes read

Question: Write a program that changes the case of each character in a string. If its uppercase, convert it to lowercase and vice-versa.

Input: ThE quiCK brOwN FOX jUMPs.
Output: tHe QUIck BRoWn fox Jumps.

In this program we shall apply the basic principle that each character is represented as an integer ASCII code. For more reference look into the post – Find the case of a character input by the user.

Now we know that
‘a’ -> ASCII CODE = 97
‘A’ -> ASCII CODE = 65
Thus the difference is => 97 – 65 = 32

Algorithm for the program:-

  • Scan the input string for each character
  • For each character, check if its lowercase or uppercase
  • If (uppercase)
    • add 32 to convert it to lower case
  • If (lowercase)
    • subtract 32 form the ASCII value

Here is an implementation of the above algorithm:-

#include<stdio.h>

void changeCase(char *str)
{
	//scan the string till we enter NULL
	while(*str != '\0')
	{
		//if upper case, we add 32
		if(65<=*str && *str<=90)
			*str += 32;

		// if lower case, we subtract 32
		else if (97<=*str && *str<=122)
			*str -= 32;

		//we need to increment to reach the next character
		str++;
		//leave all other special symbols
	}
}

int main(void)
{
	char *s=(char *)malloc(sizeof(char)*100);

	//we use this statement so that spaces are scanned
	scanf("%[^\n]s",s);

	changeCase(s);

	printf("%s",s);
	return 0;
}

You may also like

1 comment

joel sharma September 25, 2017 - 01:21

why have we used a char pointer here?

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More