Given a name as a string, the task is to find and print the initials of each word. The initials are formed by taking the first character of every word and converting it to uppercase.
- The program extracts the first character of each word to form the initials.
- This can be done by traversing the string or by splitting it into individual words.
Examples
Input: Kamlesh Joshi
Output: K J
Explanation: We take the first letter of all words and print in capital letter.
Input: Jude Law
Output: J L
Input: Abhishek Kumar Bisht
Output: A K B
Approaches to Find Initials of a Name
The initials can be found using the following approaches:
1. Traverse the String
The first character of the name is printed as an initial. Then, the string is traversed and the character immediately following each space is printed in uppercase.
#include <bits/stdc++.h>
using namespace std;
void printInitials(const string& name)
{
if (name.length() == 0)
return;
// Print the first character.
cout << (char)toupper(name[0]);
// Print the character after each space.
for (int i = 1; i < name.length() - 1; i++)
{
if (name[i] == ' ')
cout << " " << (char)toupper(name[i + 1]);
}
}
int main()
{
string name = "Kamlesh Joshi";
printInitials(name);
return 0;
}
Output
K J
Explanation
- The first character of name is converted to uppercase using toupper() and printed.
- The loop checks the remaining characters and prints the character immediately after every space as an initial.
- The function returns without printing anything if the input string is empty.
2. Using stringstream
The name can also be divided into individual words using stringstream. The first character of each extracted word is then converted to uppercase and printed.
#include <bits/stdc++.h>
using namespace std;
void printInitials(string name)
{
if (name.length() == 0)
return;
stringstream X(name);
// Extract each word and print its first character.
while (getline(X, name, ' '))
{
cout << (char)toupper(name[0]) << " ";
}
}
int main()
{
string name = "Kamlesh Joshi";
printInitials(name);
return 0;
}
Output
K J
Explanation
- stringstream is used to split the name into words using a space as the delimiter.
- getline() extracts each word from the stream.
- The first character of each word is converted to uppercase and printed.