Monday, February 17, 2020

program to change case of a string

#include <stdio.h>
#include <string.h>
int main()
{
   char string[1000];
 
   printf("Input a string to convert to lower case\n");
   gets(string);
 
   printf("The string in lower case: %s\n", strlwr(string));
 
   return  0;
}

Function strupr in C

#include <stdio.h>
#include <string.h>
int main()
{
   char string[1000];
 
   printf("Input a string to convert to upper case\n");
   gets(string);
 
   printf("The string in upper case: %s\n", strupr(string));
 
   return  0;
}

Change string to upper case without strupr

#include <stdio.h>
void upper_string(char []);
int main()
{
   char string[100];
 
   printf("Enter a string to convert it into upper case\n");
   gets(string);
 
   upper_string(string);
 
   printf("The string in upper case: %s\n", string);
   
   return 0;
}
void upper_string(char s[]) {
   int c = 0;
 
   while (s[c] != '\0') {
      if (s[c] >= 'a' && s[c] <= 'z') {
         s[c] = s[c] - 32;
      }
      c++;
   }
}

Change string to lower case without strlwr

#include <stdio.h>
void lower_string(char []);
int main()
{
   char string[100];
 
   printf("Enter a string to convert it into lower case\n");
   gets(string);
 
   lower_string(string);
 
   printf("The string in lower case: %s\n", string);
   
   return 0;
}
void lower_string(char s[]) {
   int c = 0;
 
   while (s[c] != '\0') {
      if (s[c] >= 'A' && s[c] <= 'Z') {
         s[c] = s[c] + 32;
      }
      c++;
   }
}
You can also implement functions using pointers.

C program to change the case from upper to lower and lower to upper

The following program changes the case of alphabets. If a lower/upper case alphabet is present, we convert it to upper/lower case.
#include <stdio.h>
int main ()
{
   int c = 0;
   char ch, s[1000];
   printf("Input a string\n");
   gets(s);
 
   while (s[c] != '\0') {
      ch = s[c];
      if (ch >= 'A' && ch <= 'Z')
         s[c] = s[c] + 32;
      else if (ch >= 'a' && ch <= 'z')
         s[c] = s[c] - 32; 
      c++; 
   }
 
   printf("%s\n", s);
   return 0;
}
An output of the program:
Input a string
abcdefghijklmnopqrstuvwxyz{0123456789}ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ{0123456789}abcdefghijklmnopqrstuvwxyz
If a digit or special character is present in a string, it's left as it is.

No comments:

Post a Comment