开发者

Split Paragraphs Java: i want first 50 words in one variable from string

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()));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜