Portrait of the Sleep Deprived aka. locus blog

3Dec/082

AS3: Make a wordlist from a String of words

Working on dreamgrove.org i had to turn a string of space-separated words into a word list, an array containing these words, so that when someone searches for "red dress" i could get results using the String.search() method even when these words are not adjacent to each other (eg. "... her dress was red"). So i wrote a simple function that takes that string and returns an array of the words. Here is the code:


var string:String = "Google's mission is to organize the world's information and make it universally accessible and useful";
 
function wordlist(str:String):Array{
	var wordlist:Array = new Array();
 
	while(str.search(" ") != -1){
		wordlist.push(str.substring(0, str.search(" ")));
		str = str.substr(str.search(" ")+1);
		trace(str);
	}
	wordlist.push(str);
 
	return wordlist;
}
 
trace("\nlist: "+wordlist(string));

And the output is:

mission is to organize the world's information and make it universally accessible and useful
is to organize the world's information and make it universally accessible and useful
to organize the world's information and make it universally accessible and useful
organize the world's information and make it universally accessible and useful
the world's information and make it universally accessible and useful
world's information and make it universally accessible and useful
information and make it universally accessible and useful
and make it universally accessible and useful
make it universally accessible and useful
it universally accessible and useful
universally accessible and useful
accessible and useful
and useful
useful
 
list: Google's,mission,is,to,organize,the,world's,information,and,make,it,universally,accessible,and,useful
Bookmark and Share

About Duke

locus-delicti architect
Comments (2) Trackbacks (0)
  1. Thank you thank you! So helpful.

  2. This is much cooler than you might think. I’ve already got some ideas kicking around on how I could use this.
    Really dig all the AS posts you do, btw. great stuff
    Thank you very much for sharing!


Leave a comment


No trackbacks yet.