C++ Program to Print the First Letter of Each Word of a String
Last Updated :
07 Mar, 2024
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++
// 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 = "geeks for geeks";
cout << firstLetterWord(str);
return 0;
}
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[] = "geeks for geeks";
cout << processWords(input);
return 0;
}
Time Complexity: O(N + M), where n is the length of the input string and m is the number of words.
Space Complexity: O(M + N)
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 = "geeks for geeks";
cout<< firstLetterWord(str, 0, "g");
return 0;
}
//This code is contributed by Vinay Pinjala.
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!
Similar Reads
C++ program to print unique words in a file Write a function that takes a file name as argument and prints all unique words in it. We strongly recommend you to minimize your browser and try this yourself first The idea is to use map in STL to keep track of words already occurred. C // C++ program to print unique words in a string #include
2 min read
Strings in C++ and How to Create them? Strings in C++ are used to store text or sequences of characters. In C++ strings can be stored in one of the two following ways: C-style string (using characters)String class Each of the above methods is discussed below: 1. C style string: In C, strings are defined as an array of characters. The dif
2 min read
C++ Program to count Vowels in a string using Pointer Pre-requisite: Pointers in C++ Given a string of lowercase english alphabets. The task is to count number of vowels present in a string using pointers Examples: Input : str = "geeks" Output : 2 Input : str = "geeksforgeeks" Output : 5 Approach: Initialize the string using a character array. Create a
2 min read
How to Iterate through a String word by word in C++ Given a String comprising of many words separated by space, the task is to iterate over these words of the string in C++.Example: Input: str = "GeeksforGeeks is a computer science portal for Geeks"Output: GeeksforGeeks is a computer science portal for Geeks Input: str = "Geeks for Geeks"Output: Geek
3 min read
Print a character n times without using loop, recursion or goto in C++ Given a character c and a number n, print the character c, n times. We are not allowed to use loop, recursion, and goto. Examples : Input : n = 10, c = 'a'Output : aaaaaaaaaa Input : n = 6, character = '@'Output : @@@@@@ In C++, there is a way to initialize a string with a value. It can be used to p
2 min read
Extract all integers from string in C++ Given a string, extract all integers words from it. Examples : Input : str = "geeksforgeeks 12 13 practice" Output : 12 13 Input : str = "1: Prakhar Agrawal, 2: Manish Kumar Rai, 3: Rishabh Gupta" Output : 1 2 3 Input : str = "Ankit sleeps at 4 am." Output : 4 The idea is to use stringstream:, objec
2 min read