Wednesday, March 14, 2007

Problem

Quite a common task in programming is the need to find the ASCII value of a character. The code below demonstrates how to do this in D.

Solution

int main(char[][] args) {

    auto ch        = 'A';
    int  charAsInt = ch;
    printf( "%d", charAsInt );

    return 0;
}

In D, getting the ASCII value of a character a trivial task. Simply assign the character to an integer and D will “promote” the character to reveal its ASCII value.

Some other points to note about the above code are:

  • char values in D are UTF-8 by default; if you want UTF-16 or UTF-32 characters then use the wchar or dchar types respectively.
  • Also note the use of the auto keyword when I declared the character variable, ch. The auto keyword gives you access to D implicit type inference features.
Tags: ,
posted on Wednesday, March 14, 2007 8:02:01 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
 Monday, March 05, 2007

The sample was compiled using the latest version of D, 1.007 at the time of writing. You can get the latest version of the D compiler here.

Problem

You want to break up a string into its individual tokens or words 

Solution

Use the split() function from std.string, like so:

import std.stdio;
import std.string;

void main(char[][] args)  {
     char[]   record     = "01 Barry Carr 17/04/1964 barry@notarealdomain.com";
     char[][] attributes = split(record);

     foreach( char[] attribute; attributes )
        writefln( attribute );
 }

There is on overloaded version of split() that allows you specify what characters are to be used as delimiters.

The foreach statement at the end of the code above is there so that the tokens can be displayed on the console.

Tags: ,
posted on Monday, March 05, 2007 7:02:39 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback