2011-09-27 28 views
2

分割段落的Java:我想在一个变量前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."; 

有字的总数为300

在Java中,我如何才能在第一50个字从字符串?

+1

你想前50个字,还是前50个字? – Mob

+0

你有什么尝试?你认为JavaDoc中有什么你认为可能有用的'String'类吗? –

+0

您的示例中显示的字符串中有35个单词和199个字符。没有35也没有199等于300. – DwB

回答

1

根据您的一个字的定义,这可能会为你做个空格字符,然后从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" 
} 

相关问题:

+0

这不是他想要的,他想要数字,而不是某些字符的出现。 –

+1

假设空格字符分隔单词,这是大致相同的事情。 – aioobe

+0

谢谢你的工作和我想要的东西 – user935988

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