O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Parsing a String into Words

Problem

You want to process the individual words in a string.

Solution

Use the split() method.

Discussion

The split() method, Recipe 5.6, splits a string into an array using the specified delimiter. To split a string into words, use the split() method with a space as the delimiter.

// Create a string with multiple words.
var example:String = "This is a string of words";

// Split the string into an array of words using a space as the delimiter.
var words:Array = example.split( " " );

// Loop through the array and do something with each word. 
// In this example, just output the values.
for ( var i:int = 0; i < words.length; i++ ) {
  /* Displays:
     this
     is
     a
     string
     of
     words
  */
  trace( words[i] );
}

You can process the individual words in many ways. The following is a complete example that uses this technique to split a string into words and then creates sprites containing those words. The user can then drag the words around on stage to form various sentences or statements similar to the popular magnetic poetry kits:

 package { import flash.display.Sprite; import flash.events.MouseEvent; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.display.StageAlign; import flash.display.StageScaleMode; public class ActionScriptPoetry extends Sprite { public function ActionScriptPoetry() { stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; // Create a string, and split the string into an array of words. var example:String ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required