views:

244

answers:

4

We have a string that has a maximum limit of 20 words. If the user enters something that is more than 20 words, we then need to truncate the string at its 20th word. How can we automate this? We are able to find the 20th token with #GetToken(myString, 20, ' ')#, but are unsure on how to find it's position in order to left-trim. Any ideas? Thanks in advance.

A: 

Maybe you could avoid trimming and instead rebuild the result from scratch, something like (pseudo-code, I don't know ColdFusion):

  result = ''
  for (i = 0; i < 20; ++i)
  {
     result = result + GetToken(myString, i, ' ');
  }

Would that work?

Kim Gräsman
A: 

Not sure if CF provides this, but generally there is a LastIndexOf(string token) method. Use that combined with a substring function. For isntance (psuedocode):

string lastWord = GetToken(myString, 20, ' ');
string output = Substring(mystring, 0, LastIndexOf(mystring, lastWord)+StrLength(lastWord));
JoshJordan
+8  A: 

The UDF ListLeft() should do what you want. It takes a list and returns the list with the number of elements you define. "Space" is fine as a delimiter.

p.s. CFLIB.org is an outstanding resource, and is usually my first stop when I'm looking for something like this. I recommend it highly.

Al Everett
+2  A: 

Can also use a regular expression (group #1 contains match): ^(?:\w+\s+){19}(\w+)

Michael Morton