Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to extract the first word from a string in Java?

Tags:

java

string

Trying to write a short method so that I can parse a string and extract the first word. I have been looking for the best way to do this.

I assume I would use str.split(","), however I would like to grab just the first first word from a string, and save that in one variable, and and put the rest of the tokens in another variable.

Is there a concise way of doing this?

like image 867
user476033 Avatar asked Feb 21 '11 15:02

user476033


People also ask

How do I extract the first word of a String?

FIND returns the position (as a number) of the first occurrence of a space character in the text. This position, minus one, is fed into the LEFT function as num_chars. The LEFT function then extracts characters starting at the the left side of the text, up to (position - 1).

How do you get the first letter of a String in Java as a String?

To get first character from String in Java, use String. charAt() method. Call charAt() method on the string and pass zero 0 as argument. charAt(0) returns the first character from this string.


2 Answers

The second parameter of the split method is optional, and if specified will split the target string only N times.

For example:

String mystring = "the quick brown fox"; String arr[] = mystring.split(" ", 2);  String firstWord = arr[0];   //the String theRest = arr[1];     //quick brown fox 

Alternatively you could use the substring method of String.

like image 148
Johan Sjöberg Avatar answered Oct 02 '22 17:10

Johan Sjöberg


You should be doing this

String input = "hello world, this is a line of text";  int i = input.indexOf(' '); String word = input.substring(0, i); String rest = input.substring(i); 

The above is the fastest way of doing this task.

like image 29
adarshr Avatar answered Oct 02 '22 18:10

adarshr