aspose file tools
The moose likes Java in General and the fly likes Getting the whole last word Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Getting the whole last word" Watch "Getting the whole last word" New topic
Author

Getting the whole last word

Hussein Baghdadi
clojure forum advocate
Bartender

Joined: Nov 08, 2003
Posts: 3359

Hi.
Im my web app, I want to get the newer five books from the database and display them in the index page.
At the index page, the title of the book should be displayed and a snippet of its description (lets say, the first 100 chars of its descripton).
Good example:
This book is written by .... <link>Read More</link>
Bad example :
This book is writ .... <link>Read More</link>
Do you see the problem ?
When I substring the description text, the whole last word should be included in the snippet not part of it.
Here is my small algorithm :
- use substring(0, 150)
- if the last character is a white space, then substring (0, 151)
- repeat
Do you suggest a better solution ? :roll:
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12271
    
    1
I would convert the text description to a char[], then, starting at 150, back down the char[] looking for a good end of word indicator - space, punctuation, etc. or reaching some minimum - say 120. With that index, create a new String.

This saves all that extra String object creation and lets you use characters besides whitespace as delimiters/

Bill


Java Resources at www.wbrogden.com
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Bill's solution handles non-blank terminators. If you don't need that (and you probably do) you can find a breaking point with:

content.substring(0, maxLength).lastIndexOf(" ")

I remember doing this in a language that didn't have lastIndexOf but had reverse().


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting the whole last word
 
Similar Threads
getting information (xml attribute) in frame with HTML code from other frame
methods, instances and arrays - swimming in the ocean of java
another NullPointerException problem
xsl: html: getting attribute from other frame with refresh: Update info