问题描述:

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?

网友答案:

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

网友答案:

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:

  • How to find nth occurrence of character in a string?
网友答案:

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] + " ";
网友答案:

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()));
相关阅读:
Top