String containing first letter of every word in a given string with spaces
Last Updated :
23 Apr, 2023
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/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++
#include<bits/stdc++.h>
using namespace std;
string firstLetterWord(string str)
{
string result = "" ;
bool v = true ;
for ( int i=0; i<str.length(); i++)
{
if (str[i] == ' ' )
v = true ;
else if (str[i] != ' ' && v == true )
{
result.push_back(str[i]);
v = false ;
}
}
return result;
}
int main()
{
string str = "geeks for geeks" ;
cout << firstLetterWord(str);
return 0;
}
|
Java
class GFG
{
static String firstLetterWord(String str)
{
String result = "" ;
boolean v = true ;
for ( int i = 0 ; i < str.length(); i++)
{
if (str.charAt(i) == ' ' )
{
v = true ;
}
else if (str.charAt(i) != ' ' && v == true )
{
result += (str.charAt(i));
v = false ;
}
}
return result;
}
public static void main(String[] args)
{
String str = "geeks for geeks" ;
System.out.println(firstLetterWord(str));
}
}
|
Python 3
def firstLetterWord( str ):
result = ""
v = True
for i in range ( len ( str )):
if ( str [i] = = ' ' ):
v = True
elif ( str [i] ! = ' ' and v = = True ):
result + = ( str [i])
v = False
return result
if __name__ = = "__main__" :
str = "geeks for geeks"
print (firstLetterWord( str ))
|
C#
using System;
class GFG
{
static String firstLetterWord(String str)
{
String result = "" ;
bool v = true ;
for ( int i = 0; i < str.Length; i++)
{
if (str[i] == ' ' )
{
v = true ;
}
else if (str[i] != ' ' && v == true )
{
result += (str[i]);
v = false ;
}
}
return result;
}
public static void Main()
{
String str = "geeks for geeks" ;
Console.WriteLine(firstLetterWord(str));
}
}
|
Javascript
<script>
function firstLetterWord(str)
{
let result = "" ;
let v = true ;
for (let i = 0; i < str.length; i++)
{
if (str[i] == ' ' )
{
v = true ;
}
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;
}
|
Java
public class GFG {
public static void get(String s)
{
String str = "" , temp = "" ;
for ( int i = s.length() - 1 ; i > 0 ; i--) {
if (Character.isLetter(s.charAt(i))
&& s.charAt(i - 1 ) == ' ' ) {
temp
+= s.charAt(i);
}
}
str += s.charAt( 0 );
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);
get(str2);
}
}
|
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 = "" ;
for ( int i = s.Length - 1; i > 0; i--) {
if ( char .IsLetter(s[i]) && s[i - 1] == ' ' ) {
temp += s[i];
}
}
str += s[0];
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);
Get(str2);
}
}
|
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++
#include <bits/stdc++.h>
using namespace std;
string processWords( char *input)
{
char *p;
vector<string> s;
p = strtok (input, " " );
while (p != NULL)
{
s.push_back(p);
p = strtok (NULL, " " );
}
string charBuffer;
for (string values : s)
charBuffer += values[0];
return charBuffer;
}
int main()
{
char input[] = "geeks for geeks" ;
cout << processWords(input);
return 0;
}
|
Java
class GFG
{
private static StringBuilder charBuffer = new StringBuilder();
public static String processWords(String input)
{
String s[] = input.split( "(\\s)+" );
for (String values : s)
{
charBuffer.append(values.charAt( 0 ));
}
return charBuffer.toString();
}
public static void main (String[] args)
{
String input = "geeks for geeks" ;
System.out.println(processWords(input));
}
}
|
Python3
charBuffer = []
def processWords( input ):
s = input .split( " " )
for values in s:
charBuffer.append(values[ 0 ])
return charBuffer
if __name__ = = '__main__' :
input = "geeks for geeks"
print ( * processWords( input ), sep = "")
|
C#
using System;
using System.Text;
class GFG
{
private static StringBuilder charBuffer = new StringBuilder();
public static String processWords(String input)
{
String []s = input.Split( ' ' );
foreach (String values in s)
{
charBuffer.Append(values[0]);
}
return charBuffer.ToString();
}
public static void Main()
{
String input = "geeks for geeks" ;
Console.WriteLine(processWords(input));
}
}
|
Javascript
<script>
var charBuffer = "" ;
function processWords(input)
{
var s = input.split( ' ' );
s.forEach(element => {
charBuffer+=element[0];
});
return charBuffer;
}
var input = "geeks for geeks" ;
document.write( processWords(input));
</script>
|
Time Complexity: O(n)
Auxiliary space: O(1).
Another Approach: Using boundary checker, refer https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/
Similar Reads
Get the first letter of each word in a string using regex in Java
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extr
1 min read
Print the first and last character of each word in a String
Given a string s consisting of multiple words, print the first and last character of each word. If a word contains only one character, print it twice (since the first and last characters are the same).Note: The string will not contain leading or trailing spaces. Examples: Input: s = "Geeks for geeks
5 min read
Find the first repeated word in a string in Python using Dictionary
We are given a string that may contain repeated words and the task is to find the first word that appears more than once. For example, in the string "Learn code learn fast", the word "learn" is the first repeated word. Let's understand different approaches to solve this problem using a dictionary. U
3 min read
Longest Substring containing C2, starting with C1 and ending with C3
Given a string S. Find the longest Substring that starts with character C1, ends with character C3 and has at least one character C2 in between. Print "-1" if there exists no such substring. Note: Uppercase and Lowercase letters are treated differently so 'a' and 'A' are not equivalent. Examples: In
6 min read
First non-repeating character of given string
Given a string s of lowercase English letters, the task is to find the first non-repeating character. If there is no such character, return '$'. Examples: Input: s = "geeksforgeeks"Output: 'f'Explanation: 'f' is the first character in the string which does not repeat. Input: s = "racecar"Output: 'e'
9 min read
Regex in Python to put spaces between words starting with capital letters
Given an array of characters, which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after the following amendments: Put a single space between these words. Convert the uppercase letters to
2 min read
Generate string after adding spaces at specific positions in a given String
Given a string s and an array spaces[] describing the original string's indices where spaces will be added. The task is to add spaces in given positions in spaces[] and print the string formed. Examples: Input: s = "GeeksForGeeK", spaces = {1, 5, 10}Output: "G eeks ForGe eK" Explanation: The underli
8 min read
Smallest window in a String containing all characters of other String
Given two strings s (length m) and p (length n), the task is to find the smallest substring in s that contains all characters of p, including duplicates. If no such substring exists, return "-1". If multiple substrings of the same length are found, return the one with the smallest starting index. Ex
15+ min read
Get K-th letter of the decoded string formed by repeating substrings
Given a string S containing letter and digit and an integer K where, [Tex]2\leq S.length() \leq 100 [/Tex]and [Tex]1\leq K \leq 10^{9} [/Tex]. The task is to return the K-th letter of the new string S'.The new string S' is formed from old string S by following steps: 1. If the character read is a le
6 min read
Find Strings formed by replacing prefixes of given String with given characters
Given a String ( S ) of length N and with that String, we need to print a triangle out of it. The triangle should start with the given string and keeps shrinking downwards by removing one character from the beginning of the string. The spaces on the left side of the triangle should be replaced with
9 min read