C++ Program to Find Initials of a Name
Last Updated :
27 Jan, 2023
Improve
Given a string name, we have to find the initials of the name
Examples:
Input: Kamlesh Joshi Output: K J 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
1) Print first character in capital.
2) Traverse rest of the string and print every character after space in capital letter.
// C++ program to print initials of a name
#include <bits/stdc++.h>
using namespace std;
void printInitials(const string& name)
{
if (name.length() == 0)
return;
// Since toupper() returns int,
// we do typecasting
cout << (char)toupper(name[0]);
// Traverse rest of the string and print the
// characters after spaces.
for (int i = 1; i < name.length() - 1; i++)
if (name[i] == ' ')
cout << " " << (char)toupper(name[i + 1]);
}
// Driver code
int main()
{
string name = "Kamlesh Joshi";
printInitials(name);
return 0;
}
Output:
K J
Time Complexity: O(n), Here n is the length of the string.
Auxiliary Space: O(1), As constant extra space is used.
Another possible solution is given as follows:
// C++ program to solve the
// above approach
#include <bits/stdc++.h>
using namespace std;
void printInitials(string name)
{
if (name.length() == 0)
return;
// split the string using 'space'
// and print the first character of
// every word
// X is an object of stringstream
// that references the S string
stringstream X(name);
// use while loop to check the
// getline() function condition
while (getline(X, name, ' '))
{
/* X represents to read the string from
stringstream, T use for store the
token string and, ' ' whitespace
represents to split the string where
whitespace is found. */
// Print split string
cout << (char)toupper(name[0]) << " ";
}
}
// Driver code
int main()
{
string name = "Kamlesh Joshi";
printInitials(name);
return 0;
}
Output:
K J
Time complexity: O(w), The complexity of this code will be less than O(w) where w is number of words in sentence, which can be little better than number of characters in String.
We can also use strtok() function in C/C++ to achieve this.
Auxiliary space: O(1).