Search code examples
stringd

Dlang chomp() not working on certain delimiters


The statement writefln("%s", chomp("Hello world", "orld")) produces the correct output Hello w.

However, the delimiters ":" and "," don't get chomped.

writefln("%s", chomp("Hello : world", ":"))

outputs Hello : world

The docs for std.string.chomp don't mention anything about reserved chars, unless I'm misunderstanding something. Is this a bug or working as intended?

Thanks for your time.


Solution

  • chomp strips off the ending delimiter of the string and in your case "Hello world" of course ends with "orld"

    However "Hello : world" does not end with ":" and in fact if you want it to end with anything remotely related to it then it ends with ": world"

    If this would have to work with chomp then it should be "Hello world:"

    writefln("%s", chomp("Hello world:", ":")); // It should be like this
    

    You can also use chompPrefix for starting delimiters rather than ending.

    If you want to remove ":" from the string however, then you can use replace from std.array

    writefln("%s", replace("Hello : world", ":" ""));
    // Output: "Hello  world"