Pages

Custom Search

Saturday, August 9, 2014

Program to convert string to title case

Program to convert string to title case.
In this program we are going to convert this first letter of every word in the string to UPPER CASE.
and all other letters to lower case.
This is simple but interesting program.

The LOGIC part:
Logic of the program is very simple.
Character by character parse the string from start to end of string.
Check if each letter is in proper case. If not convert it to the proper case.
SOURCE CODE:
 #include <stdio.h>  
 #include <stdlib.h>  
 int main()  
 {  
      char str[50];  
      int i, j, len;  
      printf("\nEnter a string: ");  
      gets(str);  
      printf("\nEntered string: ");  
      puts(str);  
      len=strlen(str);  
      i=0;  
      while(i!=len)                                   //til end of string  
      {  
           if((i==0))                                   //first letter of string  
           {  
                if(str[i]>90)                         //if it is not UPPER case  
                     str[i] = str[i]%65+33;  
                i++;  
           }  
           else if((str[i]!=' ') && (str[i]<=90))          //any other position than first letter of word  
           {  
                str[i]=str[i]%97+32;  
                i++;  
           }  
           else if(str[i]==' ')                    //for first letter of a word  
           {  
                i++;  
                if(str[i]>96)  
                     str[i]=str[i]%65+33;  
                i++;  
           }  
           else  
                i++;                                   //if letter is in correct case, simply increment i  
      }  
      str[i]='\0';  
      printf("\nOutput: ");  
      puts(str);  
      printf("\n\n");  
      return 1;  
 }  


SAMPLE OUTPUT

No comments:

Custom Search