String containing first letter of every word in a given string with spaces
Last Updated :
23 Jul, 2025
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 = "geeks for geeks""
Output : hc
Source: https://www.geeksforgeeks.org/interview-experiences/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.
Implementation:
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;
}
Java
// 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
# 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 Code
if __name__ == "__main__":
str = "geeks for geeks"
print(firstLetterWord(str))
# This code is contributed by ita_c
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
JavaScript
<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>
Time Complexity: O(n)
Auxiliary space: O(1).
Approach 1 : Reverse Iterative Approach
This is simplest approach to getting first letter of every word of the string. In this approach we are using reverse iterative loop to get letter of words. If particular letter ( i ) is 1st letter of word or not is can be determined by checking pervious character that is (i-1). If the pervious letter is space (' ') that means (i+1) is 1st letter then we simply add that letter to the string. Except character at 0th position. At the end we simply reverse the string and function will return string which contain 1st letter of word of the string.
C++
#include <iostream>
using namespace std;
void get(string s)
{
string str = "", temp = "";
for (int i = s.length() - 1; i > 0; i--) {
if (isalpha(s[i]) && s[i - 1] == ' ') {
temp += s[i];
}
}
str += s[0];
for (int i = temp.length() - 1; i >= 0; i--) {
str += temp[i];
}
cout << str << endl;
}
int main()
{
string str = "geeks for geeks";
string str2 = "Code of the Day";
get(str);
get(str2);
return 0;
}
// This code is contributed by sarojmcy2e
Java
public class GFG {
public static void get(String s)
{
String str = "", temp = "";
// checking condition
for (int i = s.length() - 1; i > 0; i--) {
if (Character.isLetter(s.charAt(i))
&& s.charAt(i - 1) == ' ') {
temp
+= s.charAt(i); // if consition match
// added it to the string
}
}
// adding 1st letter of string
str += s.charAt(0);
// adding remaning letters
for (int i = temp.length() - 1; i >= 0; i--) {
str += temp.charAt(i);
}
System.out.println(str);
}
public static void main(String[] args)
{
String str = "geeks for geeks";
String str2 = "Code of the Day";
get(str); // function call
get(str2); // function call
}
}
Python3
def get(s):
str = ""
temp = ""
for i in range(len(s)-1, 0, -1):
if s[i].isalpha() and s[i-1] == ' ':
temp += s[i]
str += s[0]
for i in range(len(temp)-1, -1, -1):
str += temp[i]
print(str)
str = "geeks for geeks"
str2 = "Code of the Day"
get(str)
get(str2)
C#
using System;
public class GFG {
public static void Get(string s)
{
string str = "", temp = "";
// checking condition
for (int i = s.Length - 1; i > 0; i--) {
if (char.IsLetter(s[i]) && s[i - 1] == ' ') {
temp += s[i]; // if consition match
// added it to the string
}
}
// adding 1st letter of string
str += s[0];
// adding remaning letters
for (int i = temp.Length - 1; i >= 0; i--) {
str += temp[i];
}
Console.WriteLine(str);
}
public static void Main(string[] args)
{
string str = "geeks for geeks";
string str2 = "Code of the Day";
Get(str); // function call
Get(str2); // function call
}
}
JavaScript
function get(s) {
let str = "", temp = "";
for (let i = s.length - 1; i > 0; i--) {
if (s[i].match(/[a-zA-Z]/) && s[i - 1] === ' ') {
temp += s[i];
}
}
str += s[0];
for (let i = temp.length - 1; i >= 0; i--) {
str += temp[i];
}
console.log(str);
}
const str = "geeks for geeks";
const str2 = "Code of the Day";
get(str);
get(str2);
Time Complexity: O(n)
Auxiliary space: O(1).
Approach 2: Using StringBuilder
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.
Implementation:
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;
}
// This code is contributed by
// sanjeev2552
Java
// 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";
System.out.println(processWords(input));
}
}
// This code is contributed by Goutam Das
Python3
# An efficient Python3 implementation
# of above approach
charBuffer = []
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 Code
if __name__ == '__main__':
input = "geeks for geeks"
print(*processWords(input), sep = "")
# This code is contributed
# by SHUBHAMSINGH10
C#
// C# implementation of above approach
using 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 code
public static void Main()
{
String input = "geeks for geeks";
Console.WriteLine(processWords(input));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript implementation of the above approach
var 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 code
var input = "geeks for geeks";
document.write( processWords(input));
// This code is contributed by rutvik_56.
</script>
Time Complexity: O(n)
Auxiliary space: O(1).
Another Approach: Using boundary checker, refer https://www.geeksforgeeks.org/java/get-first-letter-word-string-using-regex-java/
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem