Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Python Challenge -- Level 1 -- Native Solution

Code

import tango.io.Stdout;

void main () {
        char[] text = "".dup;

        foreach (inout char letter; text) {
                if (letter >= 'a' && letter <= 'z') {
                        letter += 2;
                        if (letter == 'y' + 2)
                                letter = 'a';
                        if (letter == 'z' + 2)
                                letter = 'b';
                }
        }
        Stdout.print(text).flush();
}

Explanation

        char[] text = "".dup;

The source text from the challenge page should be put between the quotes. dup is used because on Linux string literals are read-only.

        foreach (inout char letter; text) {
                if (letter >= 'a' && letter <= 'z') {

The code is executed for every lowercase letter.

                        letter += 2;

D allows for the direct manipulation of characters. In this case, all letter are shifted up by two.

                        if (letter == 'y' + 2)
                                letter = 'a';
                        if (letter == 'z' + 2)
                                letter = 'b';

If the letter was 'y' or 'z' in the source text, the desired result would be 'a' or 'b' in the result. However, shifting up two letters gives a different result. This corrects that by checking for those special cases and setting the letter to the desired result.

        Stdout.print(text).flush();

Print the result to the screen.