-3

Say i have a simple sentence as below.

For example, this is what have:

A simple sentence consists of only one clause. A compound sentence consists of two or more independent clauses. A complex sentence has at least one independent clause plus at least one dependent clause. A set of words with no independent clause may be an incomplete sentence, also called a sentence fragment.

I want only first 10 words in the sentence above.

I'm trying to produce the following string:

A simple sentence consists of only one clause. A compound

I tried this:

bigString.split(" " ,10).toString()

But it returns the same bigString wrapped with [] array.

Thanks in advance.

Sai
  • 15,188
  • 20
  • 81
  • 121

4 Answers4

2

If you use the split-Method with a limiter (yours is 10) it won't just give you the first 10 parts and stop but give you the first 9 parts and the 10th place of the array contains the rest of the input String. ToString concatenates all Strings from the array resulting in the whole input String. What you can do to achieve what you initially wanted is:

String[] myArray = bigString.split(" " ,11);
myArray[10] = "";   //setting the rest to an empty String
myArray.toString(); //This should give you now what you wanted but surrouned with array so just cut that off iterating the array instead of toString or something.
carrybit
  • 161
  • 9
2

Assume bigString : String equals your text. First thing you want to do is split the string in single words.

String[] words = bigString.split(" ");

How many words do you like to extract?

int n = 10;

Put words together

 String newString = "";
 for (int i = 0; i < n; i++) { newString = newString + " " + words[i];}
 System.out.println(newString);

Hope this is what you needed.

If you want to know more about regular expressions (i.e. to tell java where to split), see here: How to split a string in Java

Community
  • 1
  • 1
davidstr
  • 36
  • 3
1

This will help you

String[] strings = Arrays.stream(bigstring.split(" "))
                .limit(10)
                .toArray(String[]::new);
iamorozov
  • 761
  • 7
  • 26
1

Here is exactly what you want:

String[] result = new String[10];

// regex \s matches a whitespace character: [ \t\n\x0B\f\r]
String[] raw = bigString.split("\\s", 11);

// the last entry of raw array is the whole sentence, need to be trimmed.
System.arraycopy(raw, 0, result , 0, 10);
System.out.println(Arrays.toString(result));
Jerry Chin
  • 657
  • 1
  • 8
  • 25