EvilFactory29
EvilFactory29

Reputation: 21

Printing limited number of words in String

I am new to Java programming, and i am having a hard time with a project due in class. I have a synopsis retrieved from a netflix WSDL, and my task is to limit it from a large paragraph to only 10 words.

In other words, what code should I use to limit a large string to a specific number of words?

Upvotes: 1

Views: 1101

Answers (1)

BlackBox
BlackBox

Reputation: 2233

The only tool you really need is the String.split() method.

You split the String by a blank space delimiter, i.e. " ", if resultingArray.length <= 10 you save the first 10, discard the rest.

Simple :)

Edit: As this is not a homework service, you need to show some good faith. The usage of String.split however is seen below

public static void main(String[] args) {
    final String sentence = "This is a really, really, really, super line";
    final String[] words = sentence.split(" ");
    
    for(int i = 0; i < words.length; i++){
        System.out.printf("Word %d: %s\n", i, words[i]);
    }
}

Upvotes: 6

Related Questions