[your code here]

Jos van Uden user at domain.invalid
Sun Jan 15 08:40:06 PST 2012


On 15-1-2012 17:26, Timon Gehr wrote:
> On 01/15/2012 03:23 PM, Jos van Uden wrote:
>> import std.conv, std.traits, std.ascii;
>>
>> S rot13(S)(S s) if (isSomeString!S) {
>> return rot(s, 13);
>> }
>>
>> S rot(S)(S s, int key) if (isSomeString!S) {
>> dchar[] r = new dchar[s.length];
>>
>> foreach (i, dchar c; s) {
>> if (isLower(c))
>> c = ((c - 'a' + key) % 26 + 'a');
>> else if (isUpper(c))
>> c = ((c - 'A' + key) % 26 + 'A');
>> r[i] = c;
>> }
>> return to!S(r);
>> }
>>
>>
>> ---
>>
>> still learning this stuff, feel free to correct or improve
>>
>> Jos
>
> Your code will fail for narrow strings containing Unicode.
> dchar[] r = new dchar[s.length]; // creates a new dchar[] with as many
> elements as there are code units in the input string
>
> You can use std.range.walkLength to get the number of code points.
>
> Furthermore, that line mentions the type twice.
>
> auto r = new dchar[s.walkLength()];

Thank you.

---

S rot13(S)(S s) if (isSomeString!S) {
     return rot(s, 13);
}

S rot(S)(S s, int key) if (isSomeString!S) {
     auto r = new dchar[s.walkLength()];

     foreach (i, dchar c; s) {
         if (isLower(c))
             r[i] = ((c - 'a' + key) % 26 + 'a');
         else if (isUpper(c))
             r[i] = ((c - 'A' + key) % 26 + 'A');
     }
     return to!S(r);
}


More information about the Digitalmars-d mailing list