2

I want to to put the first letter of a string into lowercase in D.

As a string is imutable in D, there doesn't seem to be a simple way.

I came up with this:

string mystr = "BookRef";
string outval = toLower( mystr[0..1] ) ~ mystr[1..$]; 
writeln( "my outval: ", outval );

Is there an easier way ?

A.Franzen
  • 725
  • 4
  • 10

2 Answers2

6

For reference and completeness, you can build this without any allocations by chaining ranges. It has the additional advantages of working with empty strings:

auto downcase(string w)
{
    import std.range, std.uni;
    return w.take(1).asLowerCase.chain(w.drop(1));
}

Try online on run.dlang.io.

greenify
  • 1,127
  • 8
  • 7
  • I've tried this but it doesn't work with empty strings. https://run.dlang.io/is/ksDBNT. – Patrick Apr 30 '19 at 11:41
  • 1
    Sorry, `dropOne` enforces that the element is actually there, which is why it didn't work with empty strings. Updated the code to use `drop(1)` which essentially does nothing with empty strings. – greenify Apr 30 '19 at 20:13
2

While D strings are immutable, you can use char[] instead:

char[] mystr = "BookRef".dup; // .dup to create a copy
mystr[0] = toLower(mystr[0..1])[0];
writeln("my outval: ", mystr);
BioTronic
  • 2,279
  • 13
  • 15