Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

String and Number Literals

Part of TutorialIntermediate

Description

Since D 0.69, integer and floating point literals can have embedded underscores (_) for formatting purposes.

This code demonstrates those features and more...

Example

const int hundred = 100;
const int million = 1_000_000;


/*

Also added in 0.69...

x"0a AA BF" style hex strings.

*/

const string myName = x"4A 75 73 74 69 6E"; 
const string notRaw = "string\tstring";


/*

Raw (what-you-see-is-what-you-get) strings
implemented in D 0.69

*/

const string raw1 = r"string\tstring";
const string raw2 = `string\tstring`;
const string raw3 = `apostrophe: '  fancy quote: ` ~ "`";


/* See how the strings are automatically concatenated... */
const char[] oneToFive = "one" \t "two" \t "three" \t "four" \t  \t "five";


/* Binary Notation: I'm saying "two" */
const int binTwo      = 0b10;
const int binFancyTwo = 0b000_0010;

/* Hexadecimal Notation: I'm saying "16" */

const int hexSixteen      = 0x10;
const int hexFancySixteen = 0x00_10;

/* Octal Notation: I'm saying "8" */
const int octEight = 010;


int main() 
{
    /* Print "1000000" */
    writef("%i\n", million);    

    /* Print "2" */
    writef("%i\n", binTwo);  

    /* Print "16" */
    writef("%i\n", hexSixteen);  

    /* Print "8" */
    writef("%i\n", octEight);  

    /* Print "jcc7" */
    writef("%s\n", myName);   

    /* Print a string with backslashed characters */
    writef("\"Invisible\" backslashed characters: %s\n", notRaw); 

    /* Prints a what-you-see-is-what-you-get string */
    writef("What-you-see-is-what-you-get [1]: %s\n", raw1);   

    /* Prints a what-you-see-is-what-you-get string */
    writef("What-you-see-is-what-you-get [2]: %s\n", raw2);   

    /* Prints a what-you-see-is-what-you-get string */
    writef("What-you-see-is-what-you-get [3]: %s\n", raw3);   

    /* Prints one to five */
    writef("one-to-five: %s\n\n", oneToFive);

    writef("This is the first line.
This is the second line.
I'd say that D is pretty darn cool (third line).

");

    return 0;
}

Source

Link http://jcc_7.tripod.com/d/tutor/d069.html
Author jcc7