String containing first letter of every word in a given string with spaces

02 Jul, 2022
String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space. 
Examples: 
Input : str = "geeks for geeks"
Output : gfg

Input : str = "happy   coding"
Output : hc
Source: https://www.geeksforgeeks.org/amazon-interview-set-8-2/
The idea is to traverse each character of string str and maintain a boolean variable, which was initially set as true. Whenever we encounter space we set the boolean variable is true. And if we encounter any character other than space, we will check the boolean variable, if it was set as true as copy that charter to the output string and set the boolean variable as false. If the boolean variable is set false, do nothing. Algorithm: 
1. Traverse string str. And initialize a variable v as true.
2. If str[i] == ' '. Set v as true.
3. If str[i] != ' '. Check if v is true or not.
   a) If true, copy str[i] to output string and set v as false.
   b) If false, do nothing.
C++
Java
Python 3
C#
Javascript
// C++ program to find the string which contain// the first character of each word of another// string.#include<bits/stdc++.h>using namespace std; // Function to find string which has first// character of each word.string firstLetterWord(string str){    string result = "";     // Traverse the string.    bool v = true;    for (int i=0; i<str.length(); i++)    {        // If it is space, set v as true.        if (str[i] == ' ')            v = true;         // Else check if v is true or not.        // If true, copy character in output        // string and set v as false.        else if (str[i] != ' ' && v == true)        {            result.push_back(str[i]);            v = false;        }    }     return result;} // Driver codeint main(){    string str = "geeks for geeks";    cout << firstLetterWord(str);    return 0;}
// Java program to find the string which// contain the first character of each word // of another string. class GFG{         // Function to find string which has first    // character of each word.    static String firstLetterWord(String str)    {        String result = "";         // Traverse the string.        boolean v = true;        for (int i = 0; i < str.length(); i++)        {            // If it is space, set v as true.            if (str.charAt(i) == ' ')            {                v = true;            }                         // Else check if v is true or not.            // If true, copy character in output            // string and set v as false.            else if (str.charAt(i) != ' ' && v == true)            {                result += (str.charAt(i));                v = false;            }        }         return result;    }     // Driver code    public static void main(String[] args)    {        String str = "geeks for geeks";        System.out.println(firstLetterWord(str));    }} // This code is contributed by// 29AjayKumar
# Python 3 program to find the string which# contain the first character of each word# of another string. # Function to find string which has first# character of each word.def firstLetterWord(str):     result = ""     # Traverse the string.    v = True    for i in range(len(str)):                 # If it is space, set v as true.        if (str[i] == ' '):            v = True         # Else check if v is true or not.        # If true, copy character in output        # string and set v as false.        elif (str[i] != ' ' and v == True):            result += (str[i])            v = False     return result # Driver Codeif __name__ == "__main__":         str = "geeks for geeks"    print(firstLetterWord(str)) # This code is contributed by ita_c
// C# program to find the string which// contain the first character of each word// of another string.using System; class GFG{         // Function to find string which has first    // character of each word.    static String firstLetterWord(String str)    {        String result = "";         // Traverse the string.        bool v = true;        for (int i = 0; i < str.Length; i++)        {            // If it is space, set v as true.            if (str[i] == ' ')            {                v = true;            }                         // Else check if v is true or not.            // If true, copy character in output            // string and set v as false.            else if (str[i] != ' ' && v == true)            {                result += (str[i]);                v = false;            }        }        return result;    }     // Driver code    public static void Main()    {        String str = "geeks for geeks";        Console.WriteLine(firstLetterWord(str));    }} // This code is contributed by PrinciRaj1992
<script>     // Javascript program to find the string which    // contain the first character of each word    // of another string.         // Function to find string which has first    // character of each word.    function firstLetterWord(str)    {        let result = "";          // Traverse the string.        let v = true;        for (let i = 0; i < str.length; i++)        {            // If it is space, set v as true.            if (str[i] == ' ')            {                v = true;            }                          // Else check if v is true or not.            // If true, copy character in output            // string and set v as false.            else if (str[i] != ' ' && v == true)            {                result += (str[i]);                v = false;            }        }        return result;    }           let str = "geeks for geeks";      document.write(firstLetterWord(str));         </script>
Output: 
gfg
Time Complexity: O(n)
Auxiliary space: O(n). 
This approach uses the StringBuilder class of Java. In this approach, we will first split the input string based on the spaces. The spaces in the strings can be matched using a regular expression. The split strings are stored in an array of strings. Then we can simply append the first character of each split string in the String Builder object.  
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; string processWords(char *input){    /* we are splitting the input based on    spaces (s)+ : this regular expression    will handle scenarios where we have words    separated by multiple spaces */    char *p;    vector<string> s;     p = strtok(input, " ");    while (p != NULL)    {        s.push_back(p);        p = strtok(NULL, " ");    }     string charBuffer;     for (string values : s)         /* charAt(0) will pick only the first character        from the string and append to buffer */        charBuffer += values[0];     return charBuffer;} // Driver codeint main(){    char input[] = "geeks for geeks";    cout << processWords(input);    return 0;} // This code is contributed by// sanjeev2552
// Java implementation of the above approach class GFG{   private static StringBuilder charBuffer = new StringBuilder();        public static String processWords(String input)   {        /* we are splitting the input based on           spaces (s)+ : this regular expression           will handle scenarios where we have words           separated by multiple spaces */        String s[] = input.split("(\\s)+");                 for(String values : s)        {           /* charAt(0) will pick only the first character              from the string and append to buffer */            charBuffer.append(values.charAt(0));        }               return charBuffer.toString();   }       // main function   public static void main (String[] args)   {      String input = "geeks for       geeks geeks      for geeks";      System.out.println(processWords(input));   }} // This code is contributed by Goutam Das
# An efficient Python3 implementation# of above approachcharBuffer = []def processWords(input):     """ we are splitting the input based on    spaces (s)+ : this regular expression    will handle scenarios where we have words    separated by multiple spaces """    s = input.split(" ")     for values in s:        """ charAt(0) will pick only the first        character from the string and append        to buffer """        charBuffer.append(values[0])    return charBuffer # Driver Codeif __name__ == '__main__':    input = "geeks for geeks"    print(*processWords(input), sep = "") # This code is contributed# by SHUBHAMSINGH10
// C# implementation of above approachusing System;using System.Text; class GFG{ private static StringBuilder charBuffer = new StringBuilder();     public static String processWords(String input){        /* we are splitting the input based on        spaces (s)+ : this regular expression        will handle scenarios where we have words        separated by multiple spaces */        String []s = input.Split(' ');                 foreach(String values in s)        {                         /* charAt(0) will pick only the first character            from the string and append to buffer */            charBuffer.Append(values[0]);        }             return charBuffer.ToString();}     // Driver codepublic static void Main(){    String input = "geeks for geeks";    Console.WriteLine(processWords(input));}} // This code is contributed by Rajput-Ji
<script>// Javascript implementation of the above approachvar charBuffer = ""; function processWords(input){         /* we are splitting the input based on        spaces (s)+ : this regular expression        will handle scenarios where we have words        separated by multiple spaces */        var s = input.split(' ');                 s.forEach(element => {                    /* charAt(0) will pick only the first character            from the string and append to buffer */            charBuffer+=element[0];        });             return charBuffer;} // Driver codevar input = "geeks for geeks";document.write( processWords(input)); // This code is contributed by rutvik_56.</script>
Output:  
gfg
Time Complexity: O(n2)
Auxiliary space: O(n). 
Using boundary checker, refer https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/
This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
29AjayKumar
princiraj1992
Rajput-Ji
ukasp
gfg_sal_gfg
SHUBHAMSINGH10
nidhi_biet
sanjeev2552
mulchandanimanisha5
rameshtravel07
rutvik_56
akhilarora011
gulshankumarar231
codewithrathi
Amazon
School Programming
Strings
Amazon
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction To PYTHON
Interfaces in Java
Types of Operating Systems
Operator Overloading in C++
Polymorphism in C++
Write a program to reverse an array or string
Write a program to print all permutations of a given string
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
Longest Common Subsequence | DP-4