In Delphi it is possible to declare subranges for integer values. For example:
type
myInt = 2..150
Which restricts values of myInt type to values from 2 to 150. But what if I want to restrict the length of a string?
If I write:
type
myString = string [150]
I declare mystring to be 150 bytes long and restrict the length to be from 0, 1, 2, etc. up to 150. But how do I restrict the length to between 2 and 150, for example?
Of course, I can check the length of a string and raise an exception, but does Delphi include some syntax specific to this situation, similar in style to subranges?
This obviously does not work, but I would like something like:
type
myString = string[2..150]
If it is not possible, then I can just check length, raise exception, etc.
trying this code:
var
str1, str2, str3: TRestrictedString;
begin
str1.Create(2, 5, 'pp');
str2.Create(2, 5, 'aaaa');
str3.Create(2, 10, str1 + str2);
writeln (str3.getstring)
end
or:
var
str1, str2, str3: TRestrictedString;
begin
str1.Create(2, 5, 'pp');
str2.Create(2, 5, 'aaaa');
str3.Create(2, 10);
str3.SetString(str1 + str2);
writeln (str3.getstring)
end
or:
var
str1, str2, str3: TRestrictedString;
begin
str1.Create(2, 5, 'pp');
str2.Create(2, 5, 'aaaa');
str3.Create(2, 10);
str3 := str1 + str2;
writeln(str3.GetString);
end
All of these raise an exception. Is possible to solve this? For multiple operations on a string is it necessary to split the function into more parts?
In the constructor, is it better to add a check that minlength < maxlength? If I set minlength > maxlength it raises an exception.
I would do
Now you can do very natural things, like
You can also do just
You can add string the usual way:
or even
When you add two
TRestrictedStrings, or oneTRestrictedStringand astring, the result will have the same restriction as the first operand. You can trywhich will work, but not
Just beware that assigning a
stringto aTRestrictedStringwill also assign the ‘bounds’ of the string, that is, theTRestrictedStringwill have bounds set to0andMaxInt. Thus, no matter how as: TRestrictedStringis restricted, an assignments := 'some string'will always work.Update: Chris Rolliston used this answer as inspiration for a very interesting article.