# Board index » delphi » Identify digit values in a string

## Identify digit values in a string

I just wonder how to do it. Thank you.

Esky

## Re:Identify digit values in a string

##### Quote
"C. Esky" <e...@seductive.com> wrote:
>I just wonder how to do it. Thank you.
>Esky

There is more than one way so it depends on what you are doing. You can
identify the numeric chars by testing if the char is IN ['0'..'9'].
If so and if these are single digits you can use:
DigitVal := Ord(ch) - Ord('0');   (* ch is a type Char *)

You can also use VAL but in this case, ch becomes s1, a type String:
VAL(s1, DigitVal, errCode);
where errCode is an Integer and should be 0 after VAL executes. If not,
s1 is not an integer.

You can also use Turbo's POS function to obtain the digit value.
All these methods are illustrated below.

Regards,
Clif   <clifp...@airmail.net>
========================================== }

Program DigitValues;
CONST DigitChars = '0123456789';
VAR
ruler, test:String;
ct, errCode, DigitVal, sum:Integer;
ch:Char;
s1:String;
Begin

{This is for demo clarity and has nothing to do with evaluating digits}

Writeln; Writeln; Writeln;
Writeln('Math proves screen symbols are values, NOT numeric chars.');
Writeln;
test :=  '6abc9de7fg2hi3jk4lmno5pqrst8uvwx0yz1';
ruler := '123456789012345678901234567890123456';
For ct := 1 to 30 Do
If ct mod 10 = 0 then Write(ct div 10) Else Write(' ');
Writeln; Writeln(ruler); Writeln(test); Writeln;

{========== Evaluate digits in test string 3 ways ==================}

Write('Ordinal method, digit values are: ');
sum := 0;
For ct := 1 to Length(test) Do
Begin
ch := test[ct];
If ch IN ['0'..'9'] then
Begin
DigitVal := Ord(ch) - Ord('0');
Write(DigitVal:2);
sum := sum + DigitVal;
End;
End;
Writeln('.  Digit sum = ', sum);  Writeln;

Write('VAL method, digit values are:     ');
sum := 0;
For ct := 1 to Length(test) Do
Begin
s1 := test[ct];
VAL(s1, DigitVal, errCode);
If errCode = 0 then
Begin
Write(DigitVal:2);
sum := sum + DigitVal;
End;
End;
Writeln('.  Digit sum = ', sum);   Writeln;

Writeln('Using Turbo''s POS');
For ct := 1 to Length(test) Do
Begin
DigitVal := Pos(test[ct], DigitChars);
If DigitVal > 0 then
Begin
DigitVal := DigitVal - 1;
Write('Char ', ct:2 , ' has a value of ', DigitVal, '. ');
Writeln(ct:2, ' * ', DigitVal, ' = ', ct * DigitVal);
End;
End;
Writeln;
Write('Product proves digit value.  Press Enter: '); Readln;
End.

## Re:Identify digit values in a string

Hi,

var
mystring : string;
t : integer;

For t:=1 to length(mystring) do
begin
if mystring[t] in ['0','1','2','3','4','5','6','7','8','9'] then
begin
{found a digit, do stuff here}
end;
end;

regards,
Tobias

##### Quote
C. Esky wrote:
> I just wonder how to do it. Thank you.

> Esky