C++ Program to Find Initials of a Name
Last Updated :
27 Jan, 2023
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++
#include <bits/stdc++.h>
using namespace std;
void printInitials( const string& name)
{
if (name.length() == 0)
return ;
cout << ( char ) toupper (name[0]);
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
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++
#include <bits/stdc++.h>
using namespace std;
void printInitials(string name)
{
if (name.length() == 0)
return ;
stringstream X(name);
while (getline(X, name, ' ' ))
{
cout << ( char ) toupper (name[0]) << " " ;
}
}
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).
Share your thoughts in the comments
Please Login to comment...