2012-07-23 25 views
20

我有一个字符串“Magic Word”。我需要修剪字符串才能提取“魔术”。 我正在做下面的代码。在java中修剪一个字符串以获取第一个字

String sentence = "Magic Word"; 
String[] words = sentence.split(" "); 

for (String word : words) 
{ 
    System.out.println(word); 
} 

我只需要第一个单词。 是否有任何其他方法修剪字符串以获取第一个字只有在space发生?

+10

字符串firstWord = sentence.split(”“)[0]; ?? – Syam 2012-07-23 06:39:38

+0

重复的https://stackoverflow.com/questions/5067942/what-is-the-best-way-to-extract-the-first-word-from-a-string-in-java – AsfK 2017-12-07 15:44:22

回答

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

你可以使用StringreplaceAll()方法,这需要一个正则表达式作为输入,包括空间的空间后,以取代一切,如果一个空间确实存在,用空字符串:

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

一个肮脏的解决方案:

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

这有可能返回原来的字符串,如果不匹配,所以只需添加一个条件的潜力:

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

或者你可以使用一个清洁的解决方案:以上

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

两个解决方案使有关,是不是字符串在太空中第一个字符的假设是的话,这可能不是字符串是否属实从标点开始。

要采取照顾:

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

这个答案没有经过测试。如果它有些不对,请发表评论。 – nhahtdh 2012-07-23 07:00:10

5

修改以前的答案。

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

你可以试试这个 - >

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

请参阅http://stackoverflow.com/questions/5067942/what-is-the-best-way-to-extract-the-first-word-from-a-string-in-java#35345069 – GKislin 2016-02-11 16:45:18

3

这应该是最简单的方法。

public String firstWord(String string) 
{ 
return (string+" ").split(" ")[0]; //add " " to string to be sure there is something to split 
} 
3
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