3

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. What happens is that the printout when sen > 5 looks something like:

[word1, word2, word3, word4, word5]

What I want it to look like is:

word1 word2 word3 word4 word5

Any suggestion on how to convert the array to a normal sentence format as in the latter example?

Mongzyy
  • 123
  • 1
  • 10

5 Answers5

5

If you are using Java 8, you can use 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));
}
David Tanzer
  • 2,732
  • 18
  • 30
2

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
Other answers here work as well.

Some minor things to note:

To optimise slightly, you could use the optional limit parameter to String.split. 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. (Or removing that logic entirely)

ps: I believe the guard in the if statement should be lowercase array

Community
  • 1
  • 1
Anly
  • 312
  • 3
  • 11
1

You can use this method:

String sentence = TextUtils.join(" ", five);
Orkun Kocyigit
  • 1,137
  • 10
  • 21
1

Another solution, avoiding the .split() (and .join()) in the first place

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

Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75
0

try StringUtils

System.out.println(StringUtils.join(five, " "));
nafas
  • 5,283
  • 3
  • 29
  • 57