在java中修剪一个字符串以获得第一个单词
我有一个字符串“魔术词”。 我需要修剪字符串以仅提取“魔法”。 我正在做以下代码。
String sentence = "Magic Word"; String[] words = sentence.split(" "); for (String word : words) { System.out.println(word); }
我只需要第一个字。 有没有其他方法可以修剪字符串,只有在出现space
时才能得到第一个字?
String firstWord = "Magic Word"; if(firstWord.contains(" ")){ firstWord= firstWord.substring(0, firstWord.indexOf(" ")); System.out.println(firstWord); }
您可以使用String
的replaceAll()
方法,该方法将正则表达式作为输入,用空字符串替换包含空格的空格后的所有内容(如果确实存在空格):
String firstWord = sentence.replaceAll(" .*", "");
这应该是最简单的方法。
public String firstWord(String string) { return (string+" ").split(" ")[0]; //add " " to string to be sure there is something to split }
修改以前的答案。
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
脏的解决方案:
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];
你可以尝试这个 – >
String newString = "Magic Word"; int index = newString.indexOf(" "); String firstString = newString.substring(0, index); System.out.println("firstString = "+firstString);