Link to home
Start Free TrialLog in
Avatar of hulken
hulken

asked on

Check maximum possible length

How can i check the maximum possible length of a string?

What i mean is that I have a lot of variables like:

strimg[30]

string[25]

and what I want to do is to check if leng(variable) = maximum possible length
if not I want to fill it out with 0

for examplec

if string[4]  contains value abc
I want to fill it out to be 0abc

And I want to make a routinn so I can send in the variable and use generally.
Avatar of AmigoJack
AmigoJack

usually sizeof() should give you what you want. havent tested it, but sizeof() can be used for nearly all types to get its memory usage. example:

var
  s1: string[30];
  i1: byte;
begin
  i1:= sizeof(s1);  // should be 30
end;
Avatar of hulken

ASKER

How can I then do my routine?
 function PadRight(const S:String; C:Integer; Car:Char):string;
  begin
    Result:=S;
    if (Length(S)>C) then
      Result:=Copy(S, 1, C)
    else
    begin
      SetLength(Result, C);
      FillChar(Result[Length(S)+1], C, Car);
    end
  end;

procedure TForm1.Button1Click(Sender: TObject);
var
  a:string[10];
begin
  a:='some';
  a:=PadRight(a, SizeOf(a)-1, '0');
  ShowMessage(a)
end;
while length(s1)< sizeof(s1)- 1 do s1:= '0'+ s1;
hello  hulken, , I tried to make a procedure that would take any kind of shortString variable (like String[8] and String[21] and String[30] ) as a procedure parameter. . .  But I do not how to do that, and preserve the size charateristic of that declared variable? ?
So I did the following code, which will do what you want, without have the string variable as a parameter Type. . . I had to use pointers to do this in the  PadZero  procedure  below. . . .




procedure PadZero(pStr: PByte; NumChar, StrHigh: Byte);
var
pDes: PByte;
begin
// this does the Zero padding, but I used a PByte as the string type
if NumChar >= StrHigh then Exit;
pStr^ := StrHigh;
Inc(pStr);
pDes := pStr;
StrHigh := StrHigh-NumChar;
Inc(pDes, StrHigh);
MoveMemory(pDes, pStr, NumChar);
FillMemory(pStr, StrHigh, 48);
end;



procedure TForm1.ShortStr1Click(Sender: TObject);
var
Str16: String[16];
Str8: String[8];

begin
Str16 := 'Hello';
Str8 := 'Delphi?';

{I could NOT figure a way to pass a fixed string
 as a procedure parameter type and then get it's settings.
    So, you will need to use the PadZero procedure with the
    parmeters as a @ , Ord( ) and High( ) of that string}

PadZero(@Str16, Ord(Str16[0]), High(Str16));
ShowMessage(Str16);

PadZero(@Str8, Ord(Str8[0]), High(Str8));
ShowMessage(Str8);
end;


 = = = = = = = =  = = = = = = = = =
seems to work for me. . .
ask questions if you need more info
ASKER CERTIFIED SOLUTION
Avatar of AmigoJack
AmigoJack

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial