0

I'm asking if is there a way to convert a unit of a string into a char? to be more clear, is there a way to legalize this instruction:

var
    s : String;

begin
    s:='stackoverflow';
    ord(s[1]); // Illegal expression    
end.    

Getting the ASCII code from one unit of a string ( which has to be a char ) demanded a complicated algorithm in Object Pascal, can I do it in an easier way?

MEDX
  • 89
  • 8
  • 1
    Um, `s[1]` *is* a character; it's the first character in `s` (`'s'` in your case). `Ord(s[1])` *is* its codepoint (ASCII code if ASCII, `115` in your case). But the title of your question asks if it is possible to convert a string into a char. The answer is "no, unless the string happens to have length 1". But you cannot write `Ord(s[1])` as a *statement*, just like you cannot write `115` as a statement. However, `ShowMessage(IntToStr(Ord(s[1])))` works. – Andreas Rejbrand Nov 20 '20 at 19:34
  • I'm aware that s[1] is a char but getting its ASCII code ( simply ) is an illegal expression can you explain why? `Error: Illegal expression` that's what my compiler answered. – MEDX Nov 20 '20 at 19:40
  • 1
    That's because you cannot write `Ord(s[1])` as a *statement*. `Ord(s[1])` is the same thing as `115`, and you cannot have `115` as a statement: `if 1+1=2 then ShowMessage('Yes') else 115;` It's nonsense. Just try to write `Beep; 115; OpenCDTray` or whatever. – Andreas Rejbrand Nov 20 '20 at 19:41
  • 1
    @AndreasRejbrand "*`Ord(s[1])` is its codepoint*" - technically, it is a *code unit*, not a *codepoint*. Two different things. – Remy Lebeau Nov 20 '20 at 19:42
  • 1
    If you do `ShowMessage(IntToStr(Ord(s[1])))` or `Memo1.Lines.Add(IntToStr(Ord(s[1])))` it will work! – Andreas Rejbrand Nov 20 '20 at 19:43
  • 1
    @RemyLebeau: I know, but I cannot edit the comment any longer. – Andreas Rejbrand Nov 20 '20 at 19:43

1 Answers1

3

You can't use Ord(s[1]) as its own statement like you are, but you can use it as an expression within a larger statement, eg:

var
  s : String;
  i: Integer;
begin
  s := 'stackoverflow';
  i := Ord(s[1]); // i = 115
end.
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • I feel ashamed for committing such a mistake. Ord() is a function and has to return a value, sometimes I become blind. – MEDX Nov 20 '20 at 19:50
  • 2
    @CouldnoTB-Zone A function call would have compiled just fine in your example. But Ord() is an "Intrinsic Routine"(http://docwiki.embarcadero.com/RADStudio/Sydney/en/Delphi_Intrinsic_Routines) and behave more like a typecast than an actual function call. – Ken Bourassa Nov 20 '20 at 20:32