Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Divide a variable up into it's characters? 2

Status
Not open for further replies.

paulbradley

Programmer
Oct 9, 2002
158
GB

If i have a variable holding the number 1234 say, is there a way of breaking this down and holding each digit in a different variable? The same goes for strings.

Thanks.
 
If the variable is a string, it's easy.

Strings are arrays of char, you can access each char simply by adding a pointer:

writeln(yourstring[1]);

Warning: yourstring[0] holds the string length. Same as length(yourstring)

If the variable is an integer etc. you can calculate each digit OR convert it into a string using str procedure.
 
You can slo use div and mod

Code:
program divide_up;
uses crt;
var
  main, counter : integer;
  separate : array[1..20] of integer;

procedure devide(i : integer);
var count : integer;
begin
 for count := 1 to 20 do begin
 separate[count] := i mod 10; {takes the last integer}
 i := i div 10; {takes off the last integer}
 end;
end;

begin
 writeln('Enter in a number.');
 readln(main);
 devide(main);
 writeln(main,' separates into : '); 
  for counter := 1 to 20 do writeln(separate[counter]);
 readln;
end.
 
... and the str procedure will convert a number (any format, floating point or integer) into a string (you can set what sort of rounding/how many decimals).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top