We help IT Professionals succeed at work.

string problem

armoire
armoire asked
on
I am using delphi 2 and want to make sure that a string entered is of a certain length and if not i want to pad it to the correct lengh:

Problem:

I want to make sure that the characters within the string can be divided by 8 and if not add the correct number of spaces till it can be.

ie:

"this is a string" contains 16 characters so no padding is needed as it can be divided by 8 evenly.

"this is a string too" contains 20 characters and will need 4 spaces to pad it so that i can then divide it by 8 with an even result.

any one help me on this?
Comment
Watch Question

Commented:
This is a function and snippet of code which should work.

function PadRight(S: String; Ch: Char; Num: Integer): String;
begin
     while (Length(S) < Num) do
           S := S + Ch;
     PadRight := S;
end;

AString := 'this is a string too';
APaddedString := PadRight(AString, ' ', Length(AString) + (Length(AString) mod 8));

Commented:
Actually I guess that could be simplified to:

function PadString(S: String): String;
begin
     while (Length(S) mod 8 <> 0) do
           S := S + ' ';
     PadString := S;
end;

Author

Commented:
Thanks MannSoft - but will that work regardless the length of string passed to it?   Will it always check that the string is able to be divided by 8 with an even result?

Commented:
yes, because of the mod operator, it will always pad upwards to a number divisible by 8.

Commented:
MyString := MyString + StringOfChar(' ', 8 - (Length(MyString) mod 8));

Pete
====
http://www.HowToDoThings.com (Delphi articles)
http://www.Stuckindoors.com/delphi (Open source)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.