Previous Page
Next Page

Recipe 12.11. Reversing a String by Word or by Character

Problem

You want to reverse a string either by word or by character.

Solution

Use the split( ) method to create an array of the words/characters and use th e reverse( ) and join( ) methods on that array.

Discussion

You can reverse a string by word or character by using the same process. The only difference is in the delimiter you use in the split( ) method and the joiner you use in the join( ) method. In either case, the basic algorithm is:

  1. Split the string into an array, using a space as the delimiter for words or the empty string as the delimiter for characters.

  2. Call the reverse( ) method of the array, which reverses the order of the elements.

  3. Use the join( ) method to reconstruct the string. When you are reversing by word, use a space as the joiner; when reversing by character, use the empty string as the joiner:

The following code illustrates the process:

var example:String = "hello dear reader";

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

// Reverse the array.
words.reverse(  );

// Join the elements of the array into a string using spaces.
var exampleRevByWord:String = words.join( " " );

// Displays: reader dear hello
trace( exampleRevByWord );

// Split the string into an array of characters.
var characters:Array = example.split( "" );

// Reverse the array elements.
characters.reverse(  );

// Join the array elements into a string using the empty string.
var exampleRevByChar:String = characters.join( "" );

// Displays: redaer raed olleh
trace( exampleRevByChar );


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)