C++ program to capitalize first and last character of each word in a string:
One string is given. We need to capitalize first and last character of each word in this string in C++. C++ provides toupper method that can be used to convert one character to uppercase or capitalize.
We will write one for loop to iterate through the characters of the string one by one. Inside this loop, we will capitalize the character if it is:
- First or last character
- If there is a space, capitalize the character before and after it. This step is used to handle all middle words in the string.
C++ program:
Let’s write down the program:
#include <iostream>
using namespace std;
string capitalizeCharStr(string givenString)
{
for (int i = 0; i < givenString.length(); i++)
{
if (i == 0 || i == givenString.length() - 1)
{
givenString[i] = toupper(givenString[i]);
}
else if (givenString[i] == ' ')
{
givenString[i - 1] = toupper(givenString[i - 1]);
givenString[i + 1] = toupper(givenString[i + 1]);
}
}
return givenString;
}
int main()
{
string givenStr = "hello world and Hello universe ";
cout << "Given string : " << givenStr << endl;
cout << capitalizeCharStr(givenStr) << endl;
}
Explanation of this program:
- capitalizeCharStr method is used to capitalize the first and last character of each word in the string. It takes one string and returns the modified string.
- We are using one for loop to iterate through the characters of the string one by one.
- We have one if condition and one else if condition. The if condition checks if the current character is first or last. It capitalizes the character if this condition is true.
The else if block checks if the current character is a blank space. If it is a blank space, it indicates that it is the space between two words. In that case, we are capitalizing the character just before and after this blank space.
Output:
If you run the above program, it will print the below output:
Given string : hello world and Hello universe
HellO WorlD AnD HellO Universe
You can try to run the program with different types of strings.
You might also like:
- C++ program to change the case of all characters in a string
- C++ program to find out the total vowels in a string
- C++ program to count the total number of digits in a string
- C++ program to check if all characters of a string are alphanumeric or not
- How to read a string in C++ using getline
- C++ different ways to find the length of a string