ProblemYou want to reverse a string either by word or by character. SolutionUse the split( ) method to create an array of the words/characters and use th e reverse( ) and join( ) methods on that array. DiscussionYou 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:
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 ); |