In this article, we will discuss how to get first letter of every word in String in Python.
Table Of Contents
- Introduction
- Method 1: Using For Loop
- Method 2: Using List Comprehension
- Summary
Introduction
Suppose we have a string, like this,
"This is a big string to test."
We want to create a list, containing the first letter of every word in the String. Like this,
['T', 'i', 'a', 'b', 's', 't', 't']
There are different ways to do this. Let’s discuss them one by one.
Advertisements
Method 1: Using For Loop
Follow these steps to get first letter of each word in a string,
- Create an empty list to hold the first letter of each word of string.
- Split the string into a list of words using the split() method of string class.
- Iterate over each word in the list, using a for loop, and for each word, append its first letter to the list created in first point.
- Now, this new list will have the first letter of each word from the string.
Let’s see an example,
strValue = "This is a big string to test." # Split string into a list of words listOfWords = strValue.split() # List to contain first letter of each word listOfLetters = [] # Iterate over all words in list for word in listOfWords: # Select first letter of each word, and append to list listOfLetters.append(word[0]) print(listOfLetters)
Output:
['T', 'i', 'a', 'b', 's', 't', 't']
We create a list, and filled it with the first letter of every word from the string.
Method 2: Using List Comprehension
Split the string into a list of word using split() method of string class. Then iterate over all words in the list, and from each word select the first letter. Do, all this inside the List Comprehension, and build a list of first letters of each word. Let’s see an example,
strValue = "This is a big string to test." # Select first letter of each word, and append to list listOfLetters = [ word[0] for word in strValue.split()] print(listOfLetters)
Output:
['T', 'i', 'a', 'b', 's', 't', 't']
We create a list, and filled it with the first letter of every word from the string.
Summary
We learned about two different ways to fetch the first letter of each word in a string in Python. Thanks.
Here, we will develop a Python program to get the first character of a string. If the string was “Knowprogram” then print the first character “K”. We will discuss how to get the first character from the given string using native methods, and slice operator. Also, we will develop a Python program to get the first two characters of a string.
We will take a string while declaring the variables. Then, we will run the loop from 0 to 1 and append the string into the empty string (first_char). Finally, the first character will be displayed on the screen.
# Python Program get first character of string
# take input
string = input('Enter any string: ')
# get first character
first_char = ""
for i in range(0, 1):
first_char = first_char + string[i]
# printing first character of string
print('First character:', first_char)
Output for the different input values:-
Enter any string: Python
First character: P
Enter any string: Know Program
First character: K
Python Program for First Character of String
In python, String provides an [] operator to access any character in the string by index position. We need to pass the index position in the square brackets, and it will return the character at that index. As indexing of characters in a string starts from 0, So to get the first character of the given string pass the index position 0 in the [] operator i.e.
# Python Program get first character of string
# take input
string = input('Enter any string: ')
# get first character
first_char = string[0]
# printing first character of string
print('First character:', first_char)
Output:-
Enter any string: character
First character: c
Get First Character of String using Slicing
We will get the first character of the string using the slice operator. The [:1] specifies the character at index 0. The string[:1] specifies the first characters of the given string.
# Python Program get first character of string
# take input
string = input('Enter any string: ')
# get first character
first_char = string[:1]
# printing first character of string
print('First character:', first_char)
Output:-
Enter any string: first
First character: f
Python program to Get First Two Character of String
In the previous program, we will discuss how to get the first character of the string but in this program, we will discuss how to get the first two characters of the given string.
# Python Program get first two character of string
# take input
string = input('Enter any string: ')
# get first two character
first_two = string[:2]
# printing first two character of string
print('First character:', first_two)
Output:-
Enter any string: Two character
First character: Tw
Python Program for First Letter of String
This python program is different from the above program, in this program, we will print all first characters of the given string. If the string was “Know Program” then print all first characters “KP”.
# Python Program get first character from a string
# take input
string = input('Enter any string: ')
# get first character
first_char = ''.join([s[:1] for s in string.split(' ')])
# printing first character of string
print('First character:', first_char)
Output for the different input values:-
Enter any string: Know Program
First character: KP
Enter any string: First character of a string
First character: Fcoas
Also See:- Remove Special Characters from String Python
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!
$begingroup$
I’m extracting the first letter (not symbol) of a string using Unicode characters, with French words/sentences in mind.
I have implemented it like this:
def lettrine(text):
first = next((c for c in text if c.isalpha()), "")
return first
assert lettrine(u":-)") == u""
assert lettrine(u"Éléphant") == u"É"
assert lettrine(u"u03b1") == u"α"
assert lettrine(u":-)") == u""
assert lettrine(u"") == u""
Do you think there is a better solution? Would isalpha
work just as well on both Python 2.7 and 3.5?
Peilonrayz♦
42.3k7 gold badges70 silver badges151 bronze badges
asked Sep 20, 2016 at 18:15
$endgroup$
$begingroup$
The only thing I can see is that you don’t need to have the return
on a separate line. return next((c for c in text if c.isalpha()), "")
works fine. It works on both python 2 and python 3 from what I can see.
Also, you could use filter
in this situation: return next(iter(filter(unicode.isalpha, text)), "")
, although I am not sure that is any real improvement. On python 3 this approach is a bit simpler: return next(filter(str.isalpha, text), "")
answered Sep 20, 2016 at 19:33
TheBlackCatTheBlackCat
2,37410 silver badges10 bronze badges
$endgroup$
$begingroup$
According to the Python 3.5 documentation, isalpha
function return True
if all characters are letters:
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.
The Python 2.7 documentaion needs improvement (it is not clear with unicode.isalpha
): isalpha
works the same way:
$ python --version
Python 2.7.10
$ python -c 'print u"u03b1".isalpha()'
True
So, this function can extract the first letter of a unicode strings:
def lettrine(text):
return next((c for c in text if c.isalpha()), "")
answered Sep 20, 2016 at 20:55
$endgroup$
How can I merge two Python dictionaries in a single expression?
For dictionaries x
and y
, z
becomes a shallowly-merged dictionary with values from y
replacing those from x
.
-
In Python 3.9.0 or greater (released 17 October 2020): PEP-584, discussed here, was implemented and provides the simplest method:
z = x | y # NOTE: 3.9+ ONLY
-
In Python 3.5 or greater:
z = {**x, **y}
-
In Python 2, (or 3.4 or lower) write a function:
def merge_two_dicts(x, y): z = x.copy() # start with keys and values of x z.update(y) # modifies z with keys and values of y return z
and now:
z = merge_two_dicts(x, y)
Explanation
Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
The desired result is to get a new dictionary (z
) with the values merged, and the second dictionary’s values overwriting those from the first.
>>> z
{'a': 1, 'b': 3, 'c': 4}
A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is
z = {**x, **y}
And it is indeed a single expression.
Note that we can merge in with literal notation as well:
z = {**x, 'foo': 1, 'bar': 2, **y}
and now:
>>> z
{'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4}
It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into the What’s New in Python 3.5 document.
However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:
z = x.copy()
z.update(y) # which returns None since it mutates z
In both approaches, y
will come second and its values will replace x
‘s values, thus b
will point to 3
in our final result.
Not yet on Python 3.5, but want a single expression
If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the correct approach is to put it in a function:
def merge_two_dicts(x, y):
"""Given two dictionaries, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
and then you have a single expression:
z = merge_two_dicts(x, y)
You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:
def merge_dicts(*dict_args):
"""
Given any number of dictionaries, shallow copy and merge into a new dict,
precedence goes to key-value pairs in latter dictionaries.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries a
to g
:
z = merge_dicts(a, b, c, d, e, f, g)
and key-value pairs in g
will take precedence over dictionaries a
to f
, and so on.
Critiques of Other Answers
Don’t use what you see in the formerly accepted answer:
z = dict(x.items() + y.items())
In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you’re adding two dict_items
objects together, not two lists —
>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
and you would have to explicitly create them as lists, e.g. z = dict(list(x.items()) + list(y.items()))
. This is a waste of resources and computation power.
Similarly, taking the union of items()
in Python 3 (viewitems()
in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, since sets are semantically unordered, the behavior is undefined in regards to precedence. So don’t do this:
>>> c = dict(a.items() | b.items())
This example demonstrates what happens when values are unhashable:
>>> x = {'a': []}
>>> y = {'b': []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Here’s an example where y
should have precedence, but instead the value from x
is retained due to the arbitrary order of sets:
>>> x = {'a': 2}
>>> y = {'a': 1}
>>> dict(x.items() | y.items())
{'a': 2}
Another hack you should not use:
z = dict(x, **y)
This uses the dict
constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it’s difficult to read, it’s not the intended usage, and so it is not Pythonic.
Here’s an example of the usage being remediated in django.
Dictionaries are intended to take hashable keys (e.g. frozenset
s or tuples), but this method fails in Python 3 when keys are not strings.
>>> c = dict(a, **b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings
From the mailing list, Guido van Rossum, the creator of the language, wrote:
I am fine with
declaring dict({}, **{1:3}) illegal, since after all it is abuse of
the ** mechanism.
and
Apparently dict(x, **y) is going around as «cool hack» for «call
x.update(y) and return x». Personally, I find it more despicable than
cool.
It is my understanding (as well as the understanding of the creator of the language) that the intended usage for dict(**y)
is for creating dictionaries for readability purposes, e.g.:
dict(a=1, b=10, c=11)
instead of
{'a': 1, 'b': 10, 'c': 11}
Despite what Guido says,
dict(x, **y)
is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.
Again, it doesn’t work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. dict
broke this consistency in Python 2:
>>> foo(**{('a', 'b'): None})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{('a', 'b'): None})
{('a', 'b'): None}
This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.
I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.
More comments:
dict(x.items() + y.items())
is still the most readable solution for Python 2. Readability counts.
My response: merge_two_dicts(x, y)
actually seems much clearer to me, if we’re actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.
{**x, **y}
does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged […] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word «merging» these answers describe «updating one dict with another», and not merging.
Yes. I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first’s values being overwritten by the second’s — in a single expression.
Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:
from copy import deepcopy
def dict_of_dicts_merge(x, y):
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
z[key] = dict_of_dicts_merge(x[key], y[key])
for key in x.keys() - overlapping_keys:
z[key] = deepcopy(x[key])
for key in y.keys() - overlapping_keys:
z[key] = deepcopy(y[key])
return z
Usage:
>>> x = {'a':{1:{}}, 'b': {2:{}}}
>>> y = {'b':{10:{}}, 'c': {11:{}}}
>>> dict_of_dicts_merge(x, y)
{'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}}
Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at my answer to the canonical question on a «Dictionaries of dictionaries merge».
These approaches are less performant, but they will provide correct behavior.
They will be much less performant than copy
and update
or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dictionaries have precedence)
You can also chain the dictionaries manually inside a dict comprehension:
{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7
or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):
dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2
itertools.chain
will chain the iterators over the key-value pairs in the correct order:
from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2
Performance Analysis
I’m only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)
from timeit import repeat
from itertools import chain
x = dict.fromkeys('abcdefg')
y = dict.fromkeys('efghijk')
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
min(repeat(lambda: {**x, **y}))
min(repeat(lambda: merge_two_dicts(x, y)))
min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
min(repeat(lambda: dict(chain(x.items(), y.items()))))
min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
In Python 3.8.1, NixOS:
>>> min(repeat(lambda: {**x, **y}))
1.0804965235292912
>>> min(repeat(lambda: merge_two_dicts(x, y)))
1.636518670246005
>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
3.1779992282390594
>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))
2.740647904574871
>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
4.266070580109954
$ uname -a
Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux
Resources on Dictionaries
- My explanation of Python’s dictionary implementation, updated for 3.6.
- Answer on how to add new keys to a dictionary
- Mapping two lists into a dictionary
- The official Python docs on dictionaries
- The Dictionary Even Mightier — talk by Brandon Rhodes at Pycon 2017
- Modern Python Dictionaries, A Confluence of Great Ideas — talk by Raymond Hettinger at Pycon 2017
if not a:
print("List is empty")
Using the implicit booleanness of the empty list
is quite pythonic.
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 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)
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.