我有过
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个单词?
发布于 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
发布于 2011-09-27 22:08:08
根据您对单词的定义,这可能适用于您:
搜索第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"
}相关问题:
发布于 2011-09-27 22:09:35
使用正则表达式拆分传入数据,进行边界检查,然后重新构建前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] + " ";https://stackoverflow.com/questions/7570456
复制相似问题