Change A Character In A String Using Actionscript
Asked Answered
F

4

5

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.

Favoritism answered 14/5, 2010 at 2:25 Comment(0)
R
10

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);
}
Roderich answered 14/5, 2010 at 3:17 Comment(0)
N
2

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

Nightjar answered 14/5, 2010 at 9:48 Comment(0)
A
1

That answer was such a big help, but i think theres an easyer way. Suppose you want to replace the 4th character of a string called B by the letter "w". You can use

B = B.replace(B.charAt(4), "w");

Im using flash cs4 with actionscript 3.0, if it doesnt works with someone, let me know. If theres a evenbetter way of doing it let me know aswell.

Allowable answered 20/10, 2010 at 21:30 Comment(2)
This solution is not preferable, because replace() will replace the first instance it finds of the character retrieved from charAt(4) and not necessarily the instance at index 4. If B == "bellborn", it would become "wellborn" rather than "bellworn".Stewart
The charAt() method returns the character at the specified index in a string.The index of the first character is 0, the second character is 1, and so on. Hence, code has to be B = B.replace(B.charAt(3), "w");Rollo
T
1
//Replacing "/" with "-"
var str:String = "he/ll/o"
str = str.split("/").join("-"); //str = he-ll-o
Tentage answered 9/12, 2014 at 5:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.