I want to select the first N words of a text string.
I have tried split()
and substring()
to no avail.
What I want is to select the first 3 words of the following prayer and copy them to another variable.
For example if I have a string:
String greeting = "Hello this is just an example"
I want to get into the variable Z the first 3 words so that
Z = "Hello this is"
NOTE : Here .split() function returns an array of strings computed by splitting a given string around matches of the given regular expression
so if i write the code like follows
then answers will be :
1234 and 567 where stored into an array.
This is doing by storing the split values into the given array. first split value store to arr[0], second goes to arr[1].
Later part of the code is for concatenating the required number of split words
Hope that you can get an idea from this!!!
Thank you!
Add this in a utility class, such as Util.java
Usage: Util.getFirstNWords("This will give you the first N words", 3); ----> "This will give"
If you use Apache Commons Lang3, you can make it a little shorter like this:
You could try something like:
N.B. This assumes there are at least three space characters in your source string. Any less and this code will probably fail.
Now
getFirstNStrings("Hello this is just an example", 3);
will output: