codescracker
c++

C++ Program to Capitalize First Letter of Every Word in a String



« C++ Tutorial C++ Example »

This article provides a program in C++ that capitalizes first letter of every word in a string entered by user at run-time.

For example, if the string entered by user is hello, Welcome to codescracker dot com, then the output after capitalizing every word of given string looks like Hello, Welcome To Codescracker Dot Com

Capitalize First Letter of All Words

The question is, write a program in C++ that receives a string as input from user and capitalizes every word of given string. The answer to this question is:

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

using namespace std;
int main()
{
   char str[200], ch;
   int len, i, asc_val;
   cout<<"Enter the String: ";
   gets(str);
   len = strlen(str);
   for(i=0; i<len; i++)
   {
      ch = str[i];
      if(i==0)
      {
         asc_val = ch;
         if(asc_val>=97 && asc_val<=122)
         {
            asc_val = asc_val-32;
            ch = asc_val;
            str[i] = ch;
         }
      }
      if(ch==' ')
      {
         ch = str[i+1];
         asc_val = ch;
         if(asc_val>=97 && asc_val<=122)
         {
            asc_val = asc_val-32;
            ch = asc_val;
            str[i+1] = ch;
         }
      }
   }
   cout<<"\nAll words are capitalized successfully!";
   cout<<"\nThe new string is:\n\n";
   cout<<str;
   cout<<endl;
   return 0;
}

Here is the initial output produced by above C++ program on capitalizing each and every words of a given string by user at run-time:

c++ program capitalize every word in string

Now supply the string input say hello, Welcome to codescracker dot com and press ENTER key to capitalize all of its word like shown in the snapshot given below:

capitalize every word in string cpp

From above program, the statement:

len = strlen(str);

initializes the length of string to the variable len. And the statement:

ch = str[i];

initializes the character at ith index of string str to the variable ch. And the statement:

asc_val = ch;

initializes the ASCII equivalent of the character stored in ch variable. This is because, the asc_val is of int type. Again the statement given below, that is:

ch = asc_val;

initializes the character that is equivalent to the ASCII value stored in asc_val variable, to ch variable.

Note - The ASCII value of a is 97, whereas the ASCII value of z is 122.

Note - The ASCII value of A is 65, where as the ASCII value of Z is 90.

That is, to convert lowercase to uppercase (eg. c to C), just subtract 32 from its ASCII value. Therefore 99 (c) - 32 = 67 (C).

C++ Online Test


« C++ Tutorial C++ Example »



© Copyright 2021. All Rights Reserved.

CodesCracker