Nidheesh
Nidheesh

Reputation: 4562

Trim a string in java to get first word

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?

Upvotes: 31

Views: 108142

Answers (8)

pasignature
pasignature

Reputation: 585

We should never make simple things more complicated. Programming is about making complicated things simple.

string.split(" ")[0]; //the first word.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240898

  String firstWord = "Magic Word";
     if(firstWord.contains(" ")){
        firstWord= firstWord.substring(0, firstWord.indexOf(" ")); 
        System.out.println(firstWord);
     }

Upvotes: 69

Satish Sharma
Satish Sharma

Reputation: 3294

You May Try This->

  String newString = "Magic Word";
  int index = newString.indexOf(" ");
  String firstString = newString.substring(0, index);
  System.out.println("firstString = "+firstString);

Upvotes: 0

Abdelrahman Elattar
Abdelrahman Elattar

Reputation: 560

   String input = "This is a line of text";

   int i = input.indexOf(" "); // 4

   String word = input.substring(0, i); // from 0 to 3

   String rest = input.substring(i+1); // after the space to the rest of the line

Upvotes: 3

Eric
Eric

Reputation: 703

This should be the easiest way.

public String firstWord(String string)
{
return (string+" ").split(" ")[0]; //add " " to string to be sure there is something to split
}

Upvotes: 9

Maneesh Srivastava
Maneesh Srivastava

Reputation: 1387

modifying previous answer.

String firstWord = null;
if(string.contains(" ")){
firstWord= string.substring(0, string.indexOf(" ")); 
}
else{
   firstWord = string;
}

Upvotes: 6

nhahtdh
nhahtdh

Reputation: 56809

A dirty solution:

sentence.replaceFirst("\\s*(\\w+).*", "$1")

This has the potential to return the original string if no match, so just add a condition:

if (sentence.matches("\\s*(\\w+).*", "$1"))
    output = sentence.replaceFirst("\\s*(\\w+).*", "$1")

Or you can use a cleaner solution:

String parts[] = sentence.trim().split("\\s+");
if (parts.length > 0)
    output = parts[0];

The two solutions above makes assumptions about the first character that is not space in the string is word, which might not be true if the string starts with punctuations.

To take care of that:

String parts[] = sentence.trim().replaceAll("[^\\w ]", "").split("\\s+");
if (parts.length > 0)
    output = parts[0];

Upvotes: 2

rid
rid

Reputation: 63472

You could use String's replaceAll() method which takes a regular expression as input, to replace everything after the space including the space, if a space does indeed exist, with the empty string:

String firstWord = sentence.replaceAll(" .*", "");

Upvotes: 10

Related Questions