Convert First letter of each word to uppercase in C++

In this tutorial, we are going to learn how to convert the first letter of each word in a string to uppercase in C++. The format of the data required in various areas is different. But the user rarely cares for such things and they enter the data in different formats.

So there arises a situation where we need to convert first letter of each word to uppercase. Let’s see how to do this.

Also, read

Convert First letter of each word in string to uppercase in C++

Let us see an example.

Given string: this is a sample sentence for data entered
Processed string: This Is A Sample Sentence For Data Entered

You can see that there is a small difference in the given string and processed string in the above example that is the thing our program will do for us. Now let us move towards the programming part.

Methodology

The program should be able to detect a string which is stored in a character array variable as it is most important. Then it will check each word that is present in the string after which the first letter of that word is analyzed. If that letter is not in upper case then it will be converted to the same and moved to the next word and so on.

Let us move forward and see how it actually works.




Program

In order to detect various words present in the string it is required to detect spaces as they lie between two words. So this is done by using isspace() function. After detecting a word half of the work is complete. Now the first letter wil be converted to uppercase by using toupper() function.

Following is the complete code. I have written the program in CodeBlocks v 16.01 and it will work in any C++ compiler.

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

using namespace std;

int main()
{
    int check=0;                // ststus of space
    int i=0;                    // for loop

    //change the string below to convert it in required format
    char str[]="Hi i am from codespeedy";       //string
    cout<<"previous string: "<<str<<endl;

    while(str[i]){                      
        if(check==0){
            str[i]=toupper(str[i]);     //conversion of string takes place here
            check=1;
        }else if(isspace(str[i]))       // change status of check if move to another word
            check=0;
        i++;
    }
    cout<<"Processed string: "<<str<<endl;
    return 0;
}

Output 

previous string: Hi i am from codespeedy
Processed string: Hi I Am From Codespeedy

Process returned 0 (0x0)   execution time : 6.602 s
Press any key to continue.

I hope you have now understood the method and able to implement it in other languages too.


Leave a Reply

Your email address will not be published. Required fields are marked *