Thursday, October 9, 2025
HomeData Modelling & AIC++ Program to Print the First Letter of Each Word of a...

C++ Program to Print the First Letter of Each Word of a String

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 = "neveropen for neveropen"
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++




// 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 code
int main()
{
    string str = "neveropen for neveropen";
    cout << firstLetterWord(str);
    return 0;
}


Output

gfg

Output: 

gfg

Time Complexity: O(n)

Space Complexity: O(1), if space of storing resultant string is taken in account it will be O(n).

Another Approach

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 add the first character of each split string in the result.  

C++




// 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 code
int main()
{
    char input[] = "neveropen for neveropen";
    cout << processWords(input);
    return 0;
}


Output

gfg

Method: Using Recursion

C++




#include<bits/stdc++.h>
using namespace std;
  
// Function to find string which has first character of each word.
string firstLetterWord(string str, int index, string result)
{
    // base case: if index is out of range, return the modified string
    if (index == str.length())
        return result;
  
    // check for space
  
    if (str[index] == ' ')
    {
        // copy the character to result string
        result.push_back(str[index+1]);
    }
        // recursively call the function for the next index
        return firstLetterWord(str, index + 1, result);
      
}
  
// Driver code
int main()
{
    string str = "neveropen for neveropen"
   cout<< firstLetterWord(str, 0, "g");
    return 0;
}
  
//This code is contributed by Vinay Pinjala.


Output

gfg

Time Complexity: O(n)
Auxiliary Space: O(n)
Please refer complete article on String containing the first letter of every word in a given string with spaces for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32346 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6715 POSTS0 COMMENTS
Nicole Veronica
11877 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11940 POSTS0 COMMENTS
Shaida Kate Naidoo
6835 POSTS0 COMMENTS
Ted Musemwa
7094 POSTS0 COMMENTS
Thapelo Manthata
6789 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS