in reply to How do I truncate a string while preserving words?

  1. Does your string contain a space in the first N characters? If not, abort.
  2. Truncate at N+1 characters
  3. Truncate at last space or in string (use the rindex function)
sub truncate_string { my($string, $maxlength) = @_; $string = substr($string, 0, $maxlength+1); die("Can't truncate, no spaces\n") if(index($string, ' ') == -1); return substr($string, 0, rindex($string, ' ') - 1); }
All code is, of course, untested.

Replies are listed 'Best First'.
Re^2: How do I truncate a string while preserving words?
by bart (Canon) on May 11, 2007 at 11:39 UTC
    You needn't cut it if the string is not longer than maxlength. Just return the original string then.
    return substr($string, 0, rindex($string, ' ') - 1);
    I'd cut it on any whitespace, or at least, in front of the last partial word, like this:
    $string =~ s/\s*[\w\-]*$/.../; return $string;
    I'm assuming that a hyphen is a part of a word. Your idea may differ from mine.

    p.s. Hmm, that'll leave any trailing nonword/nonspace characters, for example punctuation characters, intact, making the string just one character too long.

    Perhaps this is better?

    $string =~ s/\s*(?:[\w\-]+|\W)$/.../;
    or
    $string =~ s/\s*[\w\-]+$/.../ or $string =~ s/\s*\W$/.../;