简体   繁体   English

Java - 将数组转换为句子

[英]Java - convert array to sentence

I have following method: 我有以下方法:

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));
}

As an argument I enter a sentence. 作为一个论点,我输入一个句子。 If the sentence is longer than 5 words I only want the first 5 words to be printed out. 如果句子超过5个单词,我只想打印出前5个单词。 What happens is that the printout when sen > 5 looks something like: 发生的事情是当sen> 5时的打印输出看起来像:

[word1, word2, word3, word4, word5] [word1,word2,word3,word4,word5]

What I want it to look like is: 我希望它看起来像是:

word1 word2 word3 word4 word5 word1 word2 word3 word4 word5

Any suggestion on how to convert the array to a normal sentence format as in the latter example? 有关如何将数组转换为正常句子格式的任何建议,如后一示例所示?

If you are using Java 8, you can use String.join String.join: 如果您使用的是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));
}

From the way you asked the question, it seems your problem is with joining the words. 从您提出问题的方式来看,似乎您的问题在于加入这些词语。 You can have a look at this question for that: https://stackoverflow.com/a/22474764/967748 你可以看一下这个问题: https//stackoverflow.com/a/22474764/967748
Other answers here work as well. 这里的其他答案也有效。

Some minor things to note: 一些小问题需要注意:

To optimise slightly, you could use the optional limit parameter to String.split . 要稍微优化,可以使用String.split的可选limit参数。 So you would have 所以你会的

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

You could also avoid unnecessary copying, by bringing the String[] five = ... statement inside the if . 您还可以通过在if包含String[] five = ...语句来避免不必要的复制。 (Or removing that logic entirely) (或完全删除该逻辑)

ps: I believe the guard in the if statement should be lowercase array ps:我相信if语句中的guard应该是小写array

您可以使用此方法:

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

Another solution, avoiding the .split() (and .join() ) in the first place 另一种解决方案,首先避免使用.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 can be subsituted to a string builder for performance resasons, but i don't remember the exact syntax 为了性能原因,可以将res替换为字符串构建器,但我不记得确切的语法

尝试StringUtils

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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