Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use tolower in D

Tags:

d

phobos

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 ?

like image 242
A.Franzen Avatar asked Dec 09 '25 09:12

A.Franzen


2 Answers

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.

like image 80
greenify Avatar answered Dec 12 '25 03:12

greenify


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);
like image 25
BioTronic Avatar answered Dec 12 '25 03:12

BioTronic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!