拆分段落Java:我希望字符串中的一个变量中有前50个单词

时间:2011-09-27 14:02:39

标签: java

我有

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.";

总字数为300

在Java中,如何从字符串中获取前50个单词?

4 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

根据您对单词的定义,这可能适用于您:

搜索第50个空格字符,然后将子字符串从0提取到该索引。

以下是一些示例代码:

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"
}

相关问题:

答案 2 :(得分:0)

使用正则表达式,边界检查拆分传入数据,然后重建前50个单词。

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] + " ";

答案 3 :(得分:0)

你可以尝试这样的事情(如果你想要前50个单词):

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

如果你想要前50个字符,可以这样:

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