Monday, 17 August 2009

String operations

Dealing with String sometimes gets you wonder "How can I split this?", "Can I extract that?".

Well, AS3 has some pretty function that manage to do this, but sometimes, the documentation gets you wonder how practical it is.

So here are some examples for common operations with Strings:

My string:

var myString:String="Always speak the truth, think before you speak, and write it down afterwards.";

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

1. Show the first character
var fstChar:String=myString.charAt(0);

2. Output the first 6 characters
var sixChar:String=myString.substring(0,6);

3. Output from the sixth character
var fromSixth:String=myString.substring(6);

4. Slice the string from the 8th to the 12th character (basically will to the same has the substring)
var eigthToTwelve:String=myString.slice(8,12);

5. Search for a word and output it's position
var search:String=myString.search("truth");

6. Convert all letters to lower case
var lowerCase:String=myString.toLowerCase();

7. Convert all letters to upper case
var upperCase:String=myString.toUpperCase();

8. Length of a string
var howBig:Number=myString.length;

9. Concatenation... or adding something to the string (String are not like numbers, you can't add an "a" to a "b", so the operation "a"+"b" will result in "ab")

10. Replacing text with other text (this might get trickier)
var rplcText:String=myString.replace(myString.substring(0,6),"sometimes");
(this will replace the word "Always", wich is between character 0 and 6, and replace it with the word "sometimes")

Hope it helps someone.