Better Living Through Thinking

Truncating a Sentence

Thu, 15 Feb 2007

Your problem: find the last space in a line before a given number of characters and split the sentence on that space (so as not to break a word in half).

One solution:

my $string = "This is a sentence with a variety of spaces in it from which one could choose\n";
print substr($string, 0, rindex($string, ' ', 30));

The trick is to use *rindex*, which works like this: "Start at position 30 in the string (which occurs in the middle of the word "variety") and look toward the start of the string; find the first occurance of ' ' and return its string index".

[ category: /perl | link: truncating_sentences ]

Audio Broadcast

(standby)

Moon Status

Phase: 99.97%
Illuminated: 0.00%
Age (days): 29.52
moon phase 0.999743562910282 Sun May 20 17:36:56 MDT 2012