2

I have

String explanation = "The image-search feature will start rolling out in the next few days, said Johanna Wright, a Google search director. "Every picture has a story, and we want to help you discover that story she said.";

there are total number of words are 300

In Java, how do I get the first 50 words from the string?

millimoose
  • 39,073
  • 9
  • 82
  • 134
user935988
  • 19
  • 2
  • 7

4 Answers4

1

Here you go, perfect explanation: http://www.aliaspooryorik.com/blog/index.cfm/e/posts.details/post/show-the-first-n-and-last-n-words-232

JNDPNT
  • 7,445
  • 2
  • 34
  • 40
1

Depending on your definition of a word, this may do for you:

Search for the 50:th space character, and then extract the substring from 0 to that index.

Here is some example code for you:

public static int nthOccurrence(String str, char c, int n) {
    int pos = str.indexOf(c, 0);
    while (n-- > 0 && pos != -1)
        pos = str.indexOf(c, pos+1);
    return pos;
}


public static void main(String[] args) {
    String text = "Lorem ipsum dolor sit amet.";

    int numWords = 4;
    int i = nthOccurrence(text, ' ', numWords - 1);
    String intro = i == -1 ? text : text.substring(0, i);

    System.out.println(intro); // prints "Lorem ipsum dolor sit"
}

Related question:

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
0

Split the incoming data with a regex, bounds check, then rebuild the first 50 words.

String[] words = data.split(" ");
String firstFifty = "";
int max = words.length;
if (max > 50) 
  max = 50;
for (int i = 0; i < max; ++i)
  firstFifty += words[i] + " ";
claymore1977
  • 1,385
  • 7
  • 12
0

You can try something like this (If you want the first 50 words):

String explanation="The image-search feature will start rolling out in the next few days, said Johanna Wright, a Google search director. "Every picture has a story, and we want to help you discover that story she said."

String[] words = explanation.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Math.min(50, words.length); i++)
{
 sb.append(words[i] + " ");  
}
System.out.println("The first 50 words are: " + sb.toString());

Or something like this if you want the first 50 characters:

String explanation="The image-search feature will start rolling out in the next few days, said Johanna Wright, a Google search director. "Every picture has a story, and we want to help you discover that story she said."

String truncated = explanation.subString(0, Math.min(49, explanation.length()));
npinti
  • 51,780
  • 5
  • 72
  • 96