Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change A Character In A String Using Actionscript

What is the opposite of String.charAt()??

If I Have a string:

var Str:String="Hello World";

How do I change the 5th character, for example, from a ' ' to an '_'?

I can GET the 5th character like this:

var C:String=Str.charAt(5);

But how do I SET the 5th character?

Thanks in advance.

like image 759
Joshua Avatar asked May 14 '10 02:05

Joshua


2 Answers

There are many ways to skin this cat. One, off the top of my head, would involve String.substr:

var Str:String="Hello World"
var newStr:String = Str.substr(0,5) + "_" + Str.substr(6);

or, the same as above, but more generalized:

function setCharAt(str:String, char:String,index:int):String {
    return str.substr(0,index) + char + str.substr(index + 1);
}
like image 170
Juan Pablo Califano Avatar answered Sep 30 '22 06:09

Juan Pablo Califano


you cannot set any characters. Strings in ECMAScript (including ActionScript) are immutable. One thing you can do is to construct a new string containing the desired characters, as proposed here.

However, if you plan to modify the string a lot, the best is to rather have an array of characters, that you can mutate at will. When you need to print it, you simply join it with "" as separator.

greetz
back2dos

like image 39
back2dos Avatar answered Sep 30 '22 07:09

back2dos