Alex Rivera | Logout

How to get the first element in a string?

Asked 2009-07-17T13:39:18.207
21

I'm trying to figure out a way to check a string's first element if it's either a number or not.

if not(myString[0] in [0..9]) then //Do something

The problem is that I get an error "Element 0 inaccessible - use 'Length' or 'SetLength"

Another way came to my head from my C-like exprieince - convert the first element of the string to char and check the char,but there is no difference in the compile errors.

if not(char(myString[0]) in [0..9]) then //Do something

How do I accomplish it?

Edit
Report

2 Answers

46

Strings are 1-based:

if not (myString[1] in ['0'..'9']) then // Do something
answered 2009-07-17T13:41:23.477
1

The simplest way to check to see if the first character of string is an integer, and then dispatch:

var
  iResult : integer;
begin
  if TryStrToInt( mySTring[1], iResult) then
    begin
      // handle number logic here iResult = number
    end
  else
    begin
      // handle non number logic here
    end;
end;    
answered 2009-07-17T16:33:31.467

Your Answer