Monday 17 August 2009

Strings and Arrays

Continuing my last message about "String operations" some more usefull functions to use with strings. These allow you to receive a all string and separate them into data chunks that you can put in a array. It's usefull if get data like a cvs file, where all data is separated with a comma, ou semicollom(;)

var rainbow:String="red;orange;yellow;green;cyan;blue;violet";

1. Split string into an array using the (;)
trace(rainbow.split(";"));
or
var colourArray:Array=rainbow.split(";");

This will split the string in all the colors that are separated by the ";" symbol, and put them in a array

2. Split string a few times only
trace(rainbow.split(";",3));
or
var colourArray:Array=rainbow.split(";",3);

This will do the same as above, but limited to three splits

========================================

There's another operation that is even more powerfull... the combination of Split with Join.
This allow you to search for a word in text and replace it with another

1. To remove a repeating word in text
var rainbow:String="red then comes orange then comes yellow then comes green then comes cyan then comes blue then comes violet";

rainbow=rainbow.split(" then comes ").join("");

trace(rainbow);

2. Replacing words
var rainbow:String="red then comes orange then comes yellow then comes green then comes cyan then comes blue then comes violet";

rainbow=rainbow.split(" then comes ").join(";");

trace(rainbow);

No comments:

Post a Comment