A debug class has started

forkit forkit at gmail.com
Mon Dec 13 22:43:14 UTC 2021


On Monday, 13 December 2021 at 21:13:25 UTC, H. S. Teoh wrote:
>
> What you should be doing is:
>
> 	return to!string(str[0 .. len]);
>
> Or just:
>
> 	return str[0 .. len].idup;
>
>
> T

oh.. so many different ways...(to both produce the same bug, and 
also to produce the correct output).

... it's a little mind boggling ;-)


// ----------

module test;

import std : writeln, writefln, assumeUnique;
import std.conv : to;

import core.stdc.string : strdup;
import std.string : toStringz;

void main()
{
     string str = "abc;def;ab";

     //char* w = cast(char*)str; // nope. a pointer to a string 
constant is
                                 // (supposed to be) immutable, so 
expect undefined behaviour.

     char* w = strdup(cast(char*)str); // ok
     //char* w = cast(char*)str.toStringz; // also ok
     //char* w = cast(char*)str.dup; // also ok
     //char* w = str.dup.ptr; // also ok

     writeln(replaceChar(w, str.length, ';', 'X'));
}

immutable(char)[] replaceChar(char* str, ulong len, char ch1, 
char ch2)
{
     for (ulong i = 0; i < len; i++)
     {
         if (str[i] == ch1)
         {
             writefln("Found %c at str[%d]", ch1, i); // fine
             str[i] = ch2;
         }
     }

     //return to!(immutable(char)[])(str); // nope .. issue with 
null terminator perhaps ??
     return str[0 .. len].idup; // ok
     //return str[0 .. len].dup; // also ok
     //return to!string(str[0 .. len]); // also ok
     //return assumeUnique(str[0..len]); // also ok
}


// ---------------------



More information about the Digitalmars-d-learn mailing list