Wednesday, March 14, 2007

Problem

You need to find the numeric code for a character (either ASCII or Unicode).

Solution

namespace Cookbook1_2;

interface

type
  ConsoleApp = class
  public
    class method Main;
  end;

implementation

class method ConsoleApp.Main;
begin
  var ch      : char    := 'A';
  var chAsInt : Integer := Integer(ch);
  Console.WriteLine( chAsInt );
end;

end.

The ASCII or Unicode value of character is obtained by casting the character to an Integer. Also note that I have forgo Chromes type inference and explicitly declared the type for each variable.

 

posted on Wednesday, March 14, 2007 8:58:53 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
 Monday, March 05, 2007

Problem

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

Solution

I’ll present the solution in two forms; the first will use “traditional” Object Pascal idiom, the second will make the most of Chrome’s features where appropriate. Both solutions will use the FCL’s string.Split() method.

Object Pascal Version

namespace Cookbook1_1a;

interface

type
  ConsoleApp = class
  public
    class method Main;
  end;

implementation

class method ConsoleApp.Main;
const
  Space : char = ' ';
var
  userRec    : String;
  attributes : array of String;
begin
  userRec    := '01 Barry Carr 17/04/1964
barry@notarealdomain.com';
  attributes := userRec.Split( Space );
 
  for each token : String in attributes do
      Console.WriteLine( token );
end;

end.

Chrome Version

namespace Cookbook1_1b;

interface

type
  ConsoleApp = class
  public
    class method Main;
  end;

implementation

class method ConsoleApp.Main;
const
  Space : char = ' ';
begin
  var userRec    := '01 Barry Carr 17/04/1964
barry@notarealdomain.com';
  var attributes := userRec.Split( Space );
 
  for each token in attributes do
      Console.WriteLine( token );
end;

end.

Notice how the Chrome version doesn’t have any type declarations, Chrome’s type inference is doing all the work of figuring out what the types are at compile time. One other point to note is that Chrome allows the developer to declare their variables in-line, where they are needed and does not require all local variable to be declared at the top of the method, procedure or function as classic object pascal compilers do.

Finally, the loop at the bottom is there so that I can see that the string has been split as I’d expect. A unit test would be better, however.

posted on Monday, March 05, 2007 8:50:25 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback