[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 175
  • Last Modified:

How can I extract the first word in a String?

I want to be able to extract all of the characters up until the first space in any type of sentence. How would I do this in Java?

For example:

String s1 = "This is a sentence that may vary in length and number of characters";
String s2 ="However, this time the first word is longer";
String e;
e = // Operation with s1 which results in "This"
e = // Same operation with s2 results in "However,"
0
Eindoofus
Asked:
Eindoofus
  • 3
  • 3
2 Solutions
 
CEHJCommented:
e.g.
s1 = s1.substring(0, s1.indexOf(' '));

Open in new window

0
 
for_yanCommented:
Or you can split
String [] ss = s.split("[\\s]+");

Open in new window



ss[0] will be the first word
0
 
CEHJCommented:
Of course, strictly speaking, the first word in the second string is 'However', not 'However,'
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
for_yanCommented:

You probably want first to do

s= s.trim();
otherwsie if it startes with space - you'll not get teh firs word
0
 
CEHJCommented:
:)
0
 
for_yanCommented:
In split you can add other characters which sopecarate the words:

 String [] ss = s.split("[\\s,]+"); 

Open in new window


or you in regex you can look for the end of word \b
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now