If I have a string that’s a sentence, I want to check if the first and last letter of each word are the same and find which of the words have their first and last letter the same. For example:
sentence_one = "Label the bib numbers in red."
asked Dec 19, 2018 at 15:39
6
You could use a regex:
sentence_one = "Label the bib numbers in red"
sentence_one.scan(/(b(w)w*(2)b)/i)
#=> [["Label", "L", "l"], ["bib", "b", "b"]]
b
is a word boundary, w
matches a letter (you may have to adjust this). There are 3 captures: (1) the whole word, (2) the first letter and (3) the last letter. Using 2
requires the last letter to match the first.
answered Dec 19, 2018 at 16:01
StefanStefan
108k12 gold badges140 silver badges212 bronze badges
3
This will print out all words that start with and end with the same letter (not case-sensitive)
sentence_one = "Label the bib numbers in red"
words = sentence_one.split(' ')
words.each do |word|
if word[0].downcase == word[-1].downcase
puts word
end
end
answered Dec 19, 2018 at 15:52
Alec SangerAlec Sanger
4,4021 gold badge32 silver badges53 bronze badges
3
sentence_one.scan(/S+/).select{|s| s[0].downcase == s[-1].downcase}
# => ["Label", "bib"]
answered Dec 20, 2018 at 6:21
sawasawa
164k42 gold badges273 silver badges376 bronze badges
In a comment the OP asked how one could obtain a count of words having the desired property. Here’s one way to do that. I assume that the desired property is that a word’s first and last characters are the same, though possibly of different case. Here is a way to do that that does not produce an intermediate array whose elements would be counted.
r = /
b # match a word break
(?: # begin a non-capture group
p{Alpha} # match a letter
| # or
(p{Alpha}) # match a letter in capture group 1
p{Alpha}* # match zero or more letters
1 # match the contents of capture group 1
) # end the non-capture group
b # match a word break
/ix # case-indifferent and free-spacing regex definition modes
str = "How, now is that a brown cow?"
str.gsub(r).count
#=> 2
See String#gsub, in particular the case where there is only one argument and no block is provided.
Note
str.gsub(r).to_a
#=> ["that", "a"]
str.scan(r)
#=> [["t"], [nil]]
Sometimes it is awkward to use scan
when the regular expression contains capture groups (see String#scan). Those problems often can be avoided by instead using gsub
followed by to_a
(or Enumerable#entries).
answered Dec 19, 2018 at 20:06
Cary SwovelandCary Swoveland
105k6 gold badges63 silver badges99 bronze badges
Just to add one option more splitting to array (skipping one letter words):
sentence_one = "Label the bib numbers in a red color"
sentence_one.split(' ').keep_if{ |w| w.end_with?(w[0].downcase) & (w.size > 1) }
#=> ["Label", "bib"]
answered Dec 19, 2018 at 21:32
iGianiGian
10.9k3 gold badges19 silver badges35 bronze badges
sentence_one = "Label the bib numbers in red"
puts sentence_one.split(' ').count{|word| word[0] == word[-1]} # => 1
answered Dec 19, 2018 at 19:11
steenslagsteenslag
78.5k16 gold badges136 silver badges171 bronze badges
-
#1
Strive and struggle the first «letter or letters» of both the words «is or are» the same?
-
#2
Letter/is would refer to just the s. If there were more than one letter, you’d probably state the number. The first three letters are the same.
-
#3
Letter/is would refer to just the s. If there were more than one letter, you’d probably state the number. The first three letters are the same.
So shall I say «The first letter of both the words is the same»?
-
#4
Yes. (You’d probably omit the second the.)
-
#5
I would use «are». There are two letters, the first letter of each of the two words.
The first letters of the two words are the same.
Similarly, «apple» is a five-letter word, not a four-letter word.
-
#6
So shall I say «The first letter of both the words is the same»?
That is not idiomatic. I would say, «Both words begin with the same letter.»
Examples
1. Consider ‘stupid’ and ‘sullen’. Both words begin with the same letter.
2. Consider ‘huff’ and ‘puff’. Each word begins with a different letter.
3. Consider ‘put’ and ‘punish’. Each word begins with the same two letters, ‘p’ and ‘u’.
___________________________________________________________________________________
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.
In this short guide, you will learn how to capitalize the first letter of each word in a string using Java. We have already learned to capitalize the first letter of a string in Java. But capitalizing each word in a string is a bit tricky.
Using Java 8 Streams
The easiest way to capitalize the first character of each word of a string is by using Java 8 Stream API:
String str = "welcome to java";
// uppercase first letter of each word
String output = Arrays.stream(str.split("\s+"))
.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
.collect(Collectors.joining(" "));
// print the string
System.out.println(output);
// Welcome To Java
In the above example, we first split the string into an array using the split()
method. The array is passed to Arrays.stream()
as a parameter that turns it into a Stream
object. Afterward, we use the map()
method from streams to capitalize each word before converting it back to a string using the collect()
method.
If the string is empty or null
, the above code will throw an exception. Let us write a function capitalizeAll()
that makes sure there is no exception while transforming string:
public static String capitalizeAll(String str) {
if (str == null || str.isEmpty()) {
return str;
}
return Arrays.stream(str.split("\s+"))
.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
.collect(Collectors.joining(" "));
}
Here are a few examples that use the above function to capitalize the first character of each word:
System.out.println(capitalizeAll("welcome to java")); // Welcome To Java
System.out.println(capitalizeAll("this is awesome")); // This Is Awesome
System.out.println(capitalizeAll("mcdonald in lahore")); // Mcdonald In Lahore
System.out.println(capitalizeAll(null)); // null
The above solution only changes the first letter of each word while all other characters remain the same.
Sometimes, you want to ensure that only the first character of a word is capitalized. Let us write another function capitalizeFully()
for this:
public static String capitalizeFully(String str) {
if (str == null || str.isEmpty()) {
return str;
}
return Arrays.stream(str.split("\s+"))
.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase())
.collect(Collectors.joining(" "));
}
The only difference between capitalizeAll()
and capitalizeFully()
is that the latter function explicitly changes the remaining part of the word to lowercase:
System.out.println(capitalizeFully("i aM aTTa")); // I Am Atta
System.out.println(capitalizeFully("fOo bAr")); // Foo Bar
Using String.replaceAll()
Method
If you are using Java 9 or higher, it is possible to use a regular expression with the String.replaceAll()
method to capitalize the first letter of each word in a string. The String.replaceAll()
method replaces each substring of this string that matches the given regular expression with the given replacement. Here is an example:
public static String capitalizeAll(String str) {
if (str == null || str.isEmpty()) {
return str;
}
return Pattern.compile("\b(.)(.*?)\b")
.matcher(str)
.replaceAll(match -> match.group(1).toUpperCase() + match.group(2));
}
Let us have some examples:
System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java
System.out.println(capitalizeAll("i am atta")); // I Am Atta
System.out.println(capitalizeAll(null)); // null
Using Apache Commons Text
The Apache Commons Text library is yet another option to convert the first character of each word in a string to uppercase. Add the following dependency to your build.gradle
file:
implementation 'org.apache.commons:commons-text:1.8'
For the Maven project, you need to add the following to your pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.8</version>
</dependency>
Now you can use the capitalize()
method from the WordUtils
class to capitalize each word in a string:
System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere
System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky!
System.out.println(WordUtils.capitalize(null)); // null
The good thing about WordUtils
methods is that they handle the exceptions gracefully. There won’t be any exception even if the input is null
.
The WordUtils
class also provides the capitalizeFully()
method that capitalizes the first character and turns the remaining characters of each word into lowercase:
System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar
System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue!
✌️ Like this article? Follow me on
Twitter
and LinkedIn.
You can also subscribe to
RSS Feed.
ENGLISH VOCABULARY IN USE PRE INTERMEDIATE
UNIT 20 HEALTH
A |
Common
|
||||||||||||
B |
Describing We can use I’ve got a headache. Aria’s got stomach ache. My dad suffers from [often has the pain For other I’ve got a pain Ache can also be a By the end of For stronger My throat hurts I hit my leg |
||||||||||||
C |
Serious illnesses
|
||||||||||||
|
EXERCISES
20.1 |
Look at the underlined letters in each pair of words. Is the pronunciation |
20.2 |
Complete the 1 She’s got ____-____ 2 I’ve got ____a_____ cough. 3 I’m getting ______ sore 4 Ben’s got ______ headache. 5 Luis’s got ______ temperature. 6 I’ve got ______ backache. 7 Zarita’s got ______ flu. 8 My uncle had ______ heart 9 She’s got ______ cancer. 10 I’ve got ______ pain in |
20.3 |
Complete 1 B: 2 B: 3 B: 4 B: 5 B: 6 B: 7 B: 8 B: |
20.4 |
Find five lung |
20.5 |
|
ANSWER KEY