How to find the position of the nth token

We have a line with a maximum limit of 20 words. If the user enters something more than 20 words, we need to truncate the line on the 20th word. How can we automate this? We can find the 20th token of C # GetToken (myString, 20, '') #, but are not sure how to find its position to the left finish. Any ideas? Thanks in advance.

+4
source share
4 answers

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

/** * A Left() function for lists. Returns the n leftmost elements from the specified list. * * @param list List you want to return the n leftmost elements from. * @param numElements Number of leftmost elements you want returned. * @param delimiter Delimiter for the list. Default is the comma. * @return Returns a string, * @author Rob Brooks-Bilson ( rbils@amkor.com ) * @version 1, April 24, 2002 */ function ListLeft(list, numElements){ var tempList=""; var i=0; var delimiter=","; if (ArrayLen(arguments) gt 2){ delimiter = arguments[3]; } if (numElements gte ListLen(list, delimiter)){ return list; } for (i=1; i LTE numElements; i=i+1){ tempList=ListAppend(tempList, ListGetAt(list, i, delimiter), delimiter); } return tempList; } 

ps CFLIB.org is an outstanding resource, and usually my first stop when I look for something like that. I recommend it very much.

+8
source

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

+2
source

Perhaps you could avoid cropping and rebuild the result from scratch instead, something like (pseudocode, I don't know ColdFusion):

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

Will this work?

0
source

Not sure if CF provides this, but usually there is the LastIndexOf (token) method. Use this in combination with a substring. For isntance (psuedocode):

 string lastWord = GetToken(myString, 20, ' '); string output = Substring(mystring, 0, LastIndexOf(mystring, lastWord)+StrLength(lastWord)); 
0
source

All Articles