Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Capitalize the first letter of each word of a given string

C++ String: Exercise-3 with Solution

Write a C++ program to capitalize the first letter of each word of a given string. Words must be separated by only one space.

Pictorial Presentation:

C++ Exercises: Capitalize the first letter of each word of a given string

Sample Solution:

C++ Code :

#include <iostream>
#include <string>

using namespace std;

string Capitalize_first_letter(string text) {

	for (int x = 0; x < text.length(); x++)
	{
		if (x == 0)
		{
			text[x] = toupper(text[x]);
		}
		else if (text[x - 1] == ' ')
		{
			text[x] = toupper(text[x]);
		}
	}

	return text;
}

int main() 
{
	cout << Capitalize_first_letter("Write a C++ program");
	cout << "\n" << Capitalize_first_letter("cpp string exercises");
	return 0;
}

Sample Output:

Write A C++ Program
Cpp String Exercises

Flowchart:

Flowchart: Capitalize the first letter of each word of a given string.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to change every letter in a given string with the letter following it in the alphabet (ie. a becomes b, p becomes q, z becomes a).
Next: Write a C++ program to find the largest word in a given string.

What is the difficulty level of this exercise?