Modify char in string

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 19 10:39:07 PDT 2014


On 05/19/2014 10:07 AM, Tim wrote:

 > 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[]".

That's a good thing because that string literal is immutable. If that 
code compiled you would get undefined behavior.

 > I know, I can use cast(char[])

Unfortunately, not in this case. That undefined behavior would manifest 
itself as a "Segmentation fault" on many systems. :)

 > but I don't like casts for such simple things...

What you want to do makes sense only if you have a mutable ASCII string. 
Such strings are generated at run time so the problem is usually a non 
issue:

import std.stdio;

void main()
{
     foreach (line; stdin.byLine) {
         char[] s = line.dup;    // (or .idup if you want immutable)
         s[$-1] = '.';
         writefln("Input : %s", line);
         writefln("Output: %s", s);
     }
}

Ali



More information about the Digitalmars-d-learn mailing list