Capitalize first and last letter of each word in a line | faceprep

Program to capitalize first and last letter of each word in a line is discussed here.

The basic algorithm is to keep track of the spaces and capitalize the letter before the space and after space. The first letter and the last letter of the given line should be capitalized.

There are only a few things that need to be considered:

  • More than one occurrence of spaces between two words.
  • There can be a single word like ‘a’ that needs to be capitalized.
  • There may be two words like “me” where both letters must be capitalized.

Algorithm to capitalize first and last letter of each word in a line

  1. Create and initialize a hash table.
  2. Insert the index of first letter( 0) & the index of last letter ( length-1). Length is the length of the input line.
  3. Iterate from i=0 to length-1
    Find the index of spaces that are present in the line.
    If index before spaces are not in the hash table
    Insert them into the hash table
    If index after spaces are not in the hash table
    Insert them into the hash table

  4. Capitalize the indexes present in the hash table
    line [index]-=32;
  5. //ASCII value of lower case letter -ASCII value of corresponding upper case letter=32
  6. Print the converted input line

Program to capitalize first and last letter of each word in a line

// C++ program to capitalize first and last letter of each word in a line

#include <bits/stdc++.h>
using namespace std;
void capital(char* arr, int i);
int main()
{
char sentence[100], c;
int i=0;
printf(“\nEnter the word : “);
scanf(“%c”,&c);
while(c!=’\n’)
{
sentence[i++]=c;
scanf(“%c”,&c);
}
capital(sentence,i);
return 0;
}
void capital(char* arr, int i)
{
unordered_set str;
str.insert(0); // first char index
str.insert(i-1); // last char index

for(int j=1;j<i;j++)
{
if(arr[j]==’ ‘)
{
//Last letter of word is before space & first letter of word is after space
//check index already present in hash table or not if not insert index
if(str.find(j-1)==str.end())
str.insert(j-1);
if(str.find(j+1)==str.end())
str.insert(j+1);
}
}
//capitalize the first and last char
for(auto i=str.begin(); i!=str.end(); i++)
arr[*i]-=32;
//display
for(int j=0;j<i;j++)
printf(“%c”,arr[j]);
printf(“\n”);
}

Output:

capitalize first and last letter of each word in a line