开发者

Split Paragraph in Java : Want to store paragraph after particular word address number

开发者 https://www.devze.com 2023-04-07 13:25 出处:网络
I need logic, for example 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 st

I need logic, for example 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.";

The total number of words are 300.

Now I want all strings after word number 150 in a separate string. so can you 开发者_StackOverflowgive me logic please


have your tried...

explanation.substring(beginIndex, endIndex)


There are three things that will be very helpful.

The first is the String.split(String) method. It was introduced in Java 6. It works by passing in a regex and splitting the string into tokens based on that regex.

The second is the regex "\s*" which splits on all white space.

The third is a StringBuilder which lets you build strings from other strings without massive rebuilding penalties.

So, first we need to acquire words. We can do that with the split method using our white-space regex.

String[] words = String.split("\\s*");

From there, it should be rather trivial to count off the first 150 words. You can use a for loop that starts at 150 and moves up from there.

String sentence = "";
for(int i = 150; i < words.length; i++) {
    sentence = sentence + words[i] + " ";
}

But this is very expensive because it rebuilds the string so much. We can make it better by doing this

StringBuilder sentence = "";
for(int i = 150; i < words.length; i++) {
    sentence.append(words[i]).append(" ");
}

But it all together and wa-bam, you have your sentence formatted as you want. (Just watch out for that extra space on the end!)


One way would be explanation.replaceFirst("(\\S+\\s*){0,150}", "").


You can use regex to iterate over words as in example,

Pattern regex = Pattern.compile("\\b\\w");
Matcher regexMatcher = regex.matcher(context);
while (regexMatcher.find()) {
        // if regexMatcher.groupCount()%150 == 0 then build the next string list
} 
0

精彩评论

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