简体   繁体   中英

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?

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

您可以使用StringreplaceAll()方法,该方法将正则表达式作为输入,用空字符串替换包含空格的空格后的所有内容(如果确实存在空格):

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

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
}

modifying previous answer.

String firstWord = null;
if(string.contains(" ")){
firstWord= string.substring(0, string.indexOf(" ")); 
}
else{
   firstWord = string;
}
   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

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];

You May Try This->

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM