Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim a string in java to get first word

Tags:

java

I have a String "Magic Word". I need to trim the string to extract "Magic" only. I am doing the following code.

String sentence = "Magic Word";   String[] words = sentence.split(" ");    for (String word : words)   {      System.out.println(word);   }   

I need only the first word. Is there any other methods to trim a string to get first word only if space occurs?

like image 668
Nidheesh Avatar asked Jul 23 '12 06:07

Nidheesh


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.

How do I change the first word in Java?

The Java String replaceFirst() method replaces the first substring 'regex' found that matches the given argument substring (or regular expression) with the given replacement substring. The substring matching process start from beginning of the string (index 0).


1 Answers

  String firstWord = "Magic Word";      if(firstWord.contains(" ")){         firstWord= firstWord.substring(0, firstWord.indexOf(" "));          System.out.println(firstWord);      } 
like image 169
jmj Avatar answered Sep 24 '22 13:09

jmj