Program to find the initials of a name. - GeeksforGeeks

16 Nov, 2021
Given a string name, we have to find the initials of the name 
Examples: 
Input  : prabhat kumar singh
Output : P K S
We take the first letter of all
words and print in capital letter.

Input  : Jude Law
Output : J L

Input  : abhishek kumar singh
Output : A K S
1) Print first character in capital. 2) Traverse rest of the string and print every character after space in capital letter.
C++
Java
Python
C#
PHP
Javascript
// 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 codeint main(){    string name = "prabhat kumar singh";    printInitials(name);    return 0;}
// Java program to print initials of a nameclass initials {         static void printInitials(String name)    {        if (name.length() == 0)            return;         // Since toupper() returns int,        // we do typecasting        System.out.print(Character.toUpperCase(            name.charAt(0)));         // Traverse rest of the string and        // print the characters after spaces.        for (int i = 1; i < name.length() - 1; i++)            if (name.charAt(i) == ' ')                System.out.print(" " + Character.toUpperCase(                                        name.charAt(i + 1)));    }     // Driver code    public static void main(String args[])    {        String name = "prabhat kumar singh";        printInitials(name);    }} // This code is contributed by Danish Kaleem
# Python program to print# initials of a name # user define functiondef printInitials(name):    if(len(name) == 0):        return    print(name[0].upper()),    for i in range(1, len(name) - 1):        if (name[i] == ' '):            print (name[i + 1].upper()), def main():    name = "Prabhat Kumar Singh"    printInitials(name) if __name__=="__main__":    main() # This code is contributed# by prabhat kumar singh
// C# program to print initials of a nameusing System; class initials {         static void printInitials(String name)    {        if (name.Length == 0)            return;         // Since toupper() returns int,        // we do typecasting        Console.Write(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] == ' ')                Console.Write(" " + Char.ToUpper(name[i + 1]));    }     // Driver code    public static void Main()    {        String name = "prabhat kumar singh";        printInitials(name);    }} // This code is contributed by nitin mittal.
<?php// php program to print initials of a name function printInitials($name){    if (strlen($name) == 0)        return;     // Since toupper() returns int, we do typecasting    echo strtoupper($name[0]);     // Traverse rest of the string and print the    // characters after spaces.    for ($i = 1; $i < strlen($name) - 1; $i++)        if ($name[$i] == ' ')            echo " " . strtoupper($name[$i + 1]);} // Driver code$name = "prabhat kumar singh";printInitials($name); // This code is contributed by Sam007?>
<script>    // Javascript program to print initials of a name         function printInitials(name)    {        if (name.length == 0)            return;           // Since toupper() returns int,        // we do typecasting        document.write(name[0].toUpperCase());           // Traverse rest of the string and        // print the characters after spaces.        for (let i = 1; i < name.length - 1; i++)            if (name[i] == ' ')                document.write(" " + name[i + 1].toUpperCase());    }         let name = "prabhat kumar singh";      printInitials(name);     </script>
Output: 
P K S
Another possible solution is given as follows:
C++
Java
Python3
C#
Javascript
// 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    stringstream X(name); // X is an object of stringstream                          // that references the S string     // 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. */         cout << (char)toupper(name[0])<<" "; // print split string    }} // Driver codeint main(){    string name = "prabhat kumar singh";    printInitials(name);    return 0;} // This code is contributed by gauravrajput1
// Java program to print initials of a nameclass initials {         static void printInitials(String name)    {        if (name.length() == 0)            return;         //split the string using 'space'        //and print the first character of every word        String words[] = name.split(" ");        for(String word : words) {            System.out.print(Character.toUpperCase(word.charAt(0)) + " ");        }    }     // Driver code    public static void main(String args[])    {        String name = "prabhat kumar singh";        printInitials(name);    }}
# Python3 program to print initials of a namedef printInitials(name):         if (len(name) == 0):        return     # Split the string using 'space'    # and print the first character of    # every word    words = name.split(" ")    for word in words:        print(word[0].upper(), end = " ") # Driver codeif __name__ == '__main__':         name = "prabhat kumar singh"    printInitials(name) # This code is contributed by mohit kumar 29
// C# program to print initials of a nameusing System; public class initials {         static void printInitials(String name)    {        if (name.Length == 0)            return;         //split the string using 'space'        //and print the first character of every word        String []words = name.Split(' ');        foreach(String word in words) {            Console.Write(char.ToUpper(word[0]) + " ");        }    }     // Driver code    public static void Main(String []args)    {        String name = "prabhat kumar singh";        printInitials(name);    }} // This code is contributed by gauravrajput1
<script>// javascript program to print initials of a name    function printInitials( name) {        if (name.length == 0)            return;         // split the string using 'space'        // and print the first character of every word        var words = name.split(" ");             words.forEach(myFunction);      }    function myFunction(item) { document.write((item[0].toUpperCase()) + " ");}     // Driver code        var name = "prabhat kumar singh";        printInitials(name); // This code is contributed by gauravrajput1</script>
Output: 
P K S
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. This code is contributed by Anuj KhasgiwalaWe can also use strtok() function in C/C++ to achieve this.  
YouTubeGeeksforGeeks501K subscribersProgram to find the initials of a name | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hfhTe31LfrU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Prabhat kumar singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
Sam007
prabhat kumar singh
anujkhasgiwala1
suresh07
mohit kumar 29
GauravRajput1
simranarora5sos
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Different methods to reverse a string in C/C++
Check for Balanced Brackets in an expression (well-formedness) using Stack
Convert string to char array in C++
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Reverse words in a given string
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters