• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Getting the whole last word

 
clojure forum advocate
Posts: 3479
Mac Objective C Clojure
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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:
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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().
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic