首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拆分段落Java:我想在一个变量中的前50个字从字符串

拆分段落Java:我想在一个变量中的前50个字从字符串
EN

Stack Overflow用户
提问于 2011-09-27 22:02:39
回答 4查看 2.7K关注 0票数 2

我有过

代码语言:javascript
复制
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个单词?

EN

回答 4

Stack Overflow用户

发布于 2011-09-27 22:06:10

给你,完美的解释:http://www.aliaspooryorik.com/blog/index.cfm/e/posts.details/post/show-the-first-n-and-last-n-words-232

票数 1
EN

Stack Overflow用户

发布于 2011-09-27 22:08:08

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

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

下面是一些示例代码:

代码语言:javascript
复制
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"
}

相关问题:

票数 1
EN

Stack Overflow用户

发布于 2011-09-27 22:09:35

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

代码语言:javascript
复制
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] + " ";
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7570456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档