Modify char in string
Tim via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon May 19 10:07:45 PDT 2014
On Sunday, 18 May 2014 at 19:09:52 UTC, Chris Cain wrote:
> On Sunday, 18 May 2014 at 18:55:59 UTC, Tim wrote:
>> Hi everyone,
>>
>> is there any chance to modify a char in a string like:
>
> As you've seen, you cannot modify immutables (string is an
> immutable(char)[]). If you actually do want the string to be
> modifiable, you should define it as char[] instead.
>
> Then your example will work:
>
> void main()
> {
> char[] sMyText = "Replace the last char_";
> sMyText[$ - 1] = '.';
> }
>
> If you actually want it to be immutable, you can still do it,
> but you can't modify in-place, you must create a new string
> that looks like what you want:
>
> void main()
> {
> string sMyText = "Replace the last char_";
> sMyText = sMyText[0 .. $-1] ~ ".";
> // you would do
> //sMyText[0 .. 5] ~ "." ~ sMyText[6..$];
> // to "replace" something in the 5th position
> }
>
> Note that the second method allocates and uses the GC more
> (which is perfectly fine, but not something you want to do in a
> tight loop). For most circumstances, the second method is good.
Thanks - I already tried:
void main()
{
char[] sMyText = "Replace the last char_";
sMyText[$ - 1] = '.';
}
but I always getting "Error: cannot implicitly convert expression
("Replace the last char_") of type string to char[]". I know, I
can use cast(char[]) but I don't like casts for such simple
things...
More information about the Digitalmars-d-learn
mailing list