Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: How do I truncate a string while preserving words?

by DrHyde (Prior)
on May 11, 2007 at 09:06 UTC ( [id://614852]=note: print w/replies, xml ) Need Help??


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$/.../;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://614852]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-16 13:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found