我有一个像“hello world bye Moon”这样的Java字符串,我正在寻找一种有效的方法来从中提取前两个单词。目前,我正在使用 split 方法,然后连接结果数组的前两个元素。但是,我想知道是否有更简洁有效的方法来实现这一目标。
这是我当前的代码:
public class ExtractFirstTwoWords {
public static void main(String[] args) {
String inputString = "hello world bye moon";
// Split the string into words
String[] words = inputString.split(" ");
// Check if there are at least two words
if (words.length >= 2) {
// Extract the first two words
String firstTwoWords = words[0] + " " + words[1];
System.out.println("First two words: " + firstTwoWords);
} else {
System.out.println("The input string does not contain at least two words.");
}
}
}
是否有内置的Java方法或更有效的方法来从字符串中提取前两个单词,而不需要拆分和连接字符串中的所有单词?
您还可以使用子字符串:
String string = "hello world bye moon";
String stringTwo = string.substring(0, string.indexOf(' ', string.indexOf(' ')+1));
System.out.println(stringTwo);
快速解决方案是不处理整个字符串的解决方案。想象一下,如果字符串有数千个字符长,并且有很多空格。它应该读取足够的字符来获取前两个单词。您可以使用 String.indexOf 来获取第二个空格。或者你可以自己编写如下:
public class Main{
static String firstTwoWords(String s){
int spaces = 0;
int i = 0;
for(i=0; i<s.length() && spaces < 2; i++)
if (s.charAt(i) == ' ')
spaces++;
return s.substring(0, i);
}
public static void main(String[] args) {
String s0 = "hello";
String s1 = "hello world";
String s2 = "hello world peple";
System.out.println(firstTwoWords(s0));
System.out.println(firstTwoWords(s1));
System.out.println(firstTwoWords(s2));
}
}
作为
String#split()
的替代方案,您可以使用正则表达式替换方法:
String string = "hello world bye moon";
String firstTwo = string.replaceAll("(\\w+ \\w+).*", "$1");
System.out.println(firstTwo); // hello world
阅读您的评论,似乎您实际上想要一种方法,给定一个字符串和一个数字
n
,从所述字符串中提取第一个n
单词。
这是一个使用流的快速但肮脏的版本。
public static String extractWords(String s, int howMany) {
var splitString = s.split(" ");
// TODO: make sure `howMany` is not too big
return java.util.Arrays.stream(splitString) // create stream
.limit(howMany) // take only `howMany` elements
.collect(java.util.stream.Collectors.joining(" ")); // re-join with spaces
}
还有带有子数组的版本
public static String extractWords(String s, int howMany) {
var splitString = s.split(" ");
// TODO: make sure `howMany` is not too big
var subArray = java.util.Arrays.copyOf(splitString, howMany); // extract sub array
return String.join(" ", subArray); // return joined strings
}
在这两个版本中,检查参数是否有效(即字符串不为空并且有足够的单词可返回)留给读者作为练习