Java - 将数组转换为句子

3
我有以下方法:
public static void sentence(String sen)
{

    String[] array = sen.split(" ");
    String[] five = Arrays.copyOfRange(Array, 0, 5);

    if (Array.length < 6)
        System.out.println(sen);
    else
        System.out.print(Arrays.toString(five));
}

作为参数,我输入了一个句子。如果这个句子超过5个单词,我只想打印出前5个单词。当句子长度大于5时,打印输出看起来像这样:

[word1, word2, word3, word4, word5]

。我希望它看起来像这样:

word1 word2 word3 word4 word5

。你有什么建议将数组转换为后面例子中的普通句子格式吗?
5个回答

5
如果您正在使用Java 8,您可以使用String.join方法:String.join
public static void sentence(String sen) {
    String[] array = sen.split(" ");
    String[] five = Arrays.copyOfRange(Array, 0, 5);

    if (Array.length < 6)
        System.out.println(sen);
    else
        System.out.print(String.join(" ",five));
}

1
如果只需要前五个,为什么要进行所有的拆分和连接?如果数组非常长怎么办? - Viktor Mellgren

2

从您提出问题的方式来看,似乎您的问题在于如何拼接单词。您可以查看以下问题:https://dev59.com/onI_5IYBdhLWcg3wHvU5#22474764
这里的其他答案也可以解决问题。

需要注意的一些小事情:

为了稍微优化,您可以使用String.split的可选参数limit。所以您会有:

String[] array = sen.split(" ", 6); //five words + "all the rest" string

您可以通过将String[] five = ...语句放在if语句内部(或完全删除该逻辑)来避免不必要的复制。

附注:我认为if语句中的保护应该是小写的array


1

另一种解决方案是避免首先使用.split()(和.join())。

String res = "";
Scanner sc = new Scanner(sen); //Default delimiter is " "
int i = 0;
while(sc.hasNext() && i<5){
    res += sc.next();
    i++;
}
System.out.println(res);

为了提高性能,可以将res替换为字符串构建器,但我不记得确切的语法。


1
你可以使用这个方法:

String sentence = TextUtils.join(" ", five);

2
他如果没有导入必要的库就无法使用它。你应该提一下这个。 - kupsef

0

尝试 StringUtils

System.out.println(StringUtils.join(five, " "));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接