Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate string to the first n words

Tags:

string

ruby

What's the best way to truncate a string to the first n words?

like image 453
pagid Avatar asked Jun 04 '11 08:06

pagid


People also ask

How do you truncate a string?

Truncate the string (first argument) if it is longer than the given maximum string length (second argument) and return the truncated string with a ... ending. The inserted three dots at the end should also add to the string length.

How do I truncate in Word?

About truncation and wildcards Truncation, also called stemming, is a technique that broadens your search to include various word endings and spellings. To use truncation, enter the root of a word and put the truncation symbol at the end. The database will return results that include any ending of that root word.

How do I truncate a string in Python?

The other way to truncate a string is to use a rsplit() python function. rsplit() function takes the string, a delimiter value to split the string into parts, and it returns a list of words contained in the string split by the provided delimiter.

How do you split the first 5 characters of a string?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.


2 Answers

n = 3 str = "your long    long   input string or whatever" str.split[0...n].join(' ')  => "your long long"   str.split[0...n] # note that there are three dots, which excludes n  => ["your", "long", "long"] 
like image 145
Tilo Avatar answered Oct 14 '22 10:10

Tilo


You could do it like this:

s     = "what's the best way to truncate a ruby string to the first n words?" n     = 6 trunc = s[/(\S+\s+){#{n}}/].strip 

if you don't mind making a copy.

You could also apply Sawa's Improvement (wish I was still a mathematician, that would be a great name for a theorem) by adjusting the whitespace detection:

trunc = s[/(\s*\S+){#{n}}/] 

If you have to deal with an n that is greater than the number of words in s then you could use this variant:

s[/(\S+(\s+)?){,#{n}}/].strip 
like image 22
mu is too short Avatar answered Oct 14 '22 09:10

mu is too short