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:
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:
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?