Capitalize the First and Last Character of Each Word in a String


Introduction

In this tutorial, we implement an approach to capitalizing the first and last characters of each word in the input string. By iterating over the input string str, each word's starting and ending letters are capitalized. We implement this problem using C++ programming in two ways. Let's start this tutorial with some demonstrations.

Demonstration 1

String = “coding world”

Output

CodinG WorlD

In the above demonstration, consider the input string and the result after capitalizing the starting and ending character of each word of the string is CodinG WorlD.

Demonstration 2

String = “`hello all”

Output

hellO AlL

In the above demonstration, the input string is “hello all". The result after capitalizing the starting and ending characters of each word in the string is hellO AlL.

C++ Library Functions

length(): It is a string class library function and is defined in the C++ standard library. It returns the length of the input string in bytes. The length of the string is the total number of characters in the string.

Syntax

string_name.length();

isalpha(): This built-in library function is defined in the <ctype> header file. It checks whether the string characters are alphabet or not. When the characters of the string are alphabets, it returns an integer value else it returns zero.

Syntax

isalpha(char);

toupper() : This C++ library function is defined in the <cctype> header file. It converts lowercase characters to uppercase.

Syntax

toupper(char);

Algorithm

  • Take an input string.

  • Take an array of strings.

  • Use a for loop to iterate over all characters in the input string.

  • Check and capitalize the first and last character of each word in the string.

  • If the first and last character is capital, move to the next character.

  • Check for white spaces and non-alphabetical characters.

  • Print the resulting string.

Example 1

Here, we implement one of the above examples. The function capitalizeString() returns the resulting string. In the for loop, a string newString is used as an equivalent to the input string. Each alphabet of the input string is iterated over in the for loop.

#include<bits/stdc++.h>
using namespace std;

string capitalizeString(string s)
{

	// Creating an string similar to input string
	string newStr = s;
	for (int x = 0; x < newStr.length(); x++)
	{
		int l = x;
		while (x < newStr.length() && newStr[x] != ' ')
			x++;

		// Checking if character is capital or not

		newStr[l] = (char)(newStr[l] >= 'a' && newStr[l] <= 'z'
						? ((int)newStr[l] - 32)
						: (int)newStr[l]);

		newStr[x - 1] = (char)(newStr[x - 1] >= 'a' && newStr[x - 1] <= 'z'
							? ((int)newStr[x - 1] - 32)
							: (int)newStr[x - 1]);
	}

	return newStr;
}


int main()
{
	string s = "hello tutorials point";
	//cout << s << "\n";
	cout << "Resulting string after capitalizing the first and last alphabet of each word is : "<<capitalizeString(s);
}

Output

Resulting string after capitalizing the first and last alphabet of each word is : HellO TutorialS PoinT

Example 2

Implement the task of capitalizing the first and last characters of each word in a string. The user-defined function capitalizeString() iterates over each character of the string and checks the first and last character of the word. On reaching them it capitalizes the characters. The capitalized words are stored in the result variable and return the result.

#include <iostream>
#include <string>
#include <cctype> 
using namespace std;

string capitalizeString(string str)
{
   // Flag to track if the current character is the first character of a word
    bool newWord = true; 

    for (size_t x = 0; x < str.length(); ++x) 
    {
        if (isalpha(str[x]))
        {
            // Check if the character is alphabetic
            if (newWord) 
            {
              // Capitalize the first character of the word
                str[x] = toupper(str[x]); 
                newWord = false;
            }
            if (x + 1 == str.length() || !isalpha(str[x + 1])) 
            {
               // Capitalize the last character of the word
                str[x] = toupper(str[x]); 
                newWord = true;
            }
        }
        else 
        {
            newWord = true;
        }
    }
    return str;
}

int main() 
{
    string str = "hello coding world";

    string result = capitalizeString(str);
    cout << "Resulting string after capitalizing first and last character is:  " << result << endl;

    return 0;
}

Output

Resulting string after capitalizing first and last character is: HellO CodinG WorlD

Conclusion

We have reached the end of this tutorial. In this tutorial, we learned an approach to capitalizing the first and end character of each word in the input string. We implemented the approach through two C++ codes. Using different C++ library functions like length(), isalpha(), and toupper() to implement the problem.

Updated on: 18-Aug-2023

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements