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/
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.