0% found this document useful (0 votes)
20 views4 pages

Ex 0004

Uploaded by

skamelrech2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views4 pages

Ex 0004

Uploaded by

skamelrech2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

178 - 06: All About Strings

Inc (NCount); // found one


until I < 0;

Show('O found: ' +


NCount.ToString + ' times');
I know the repeat loop is not the simplest one: it starts with a negative index, as any
following search begins with the index after the current one; it counts occurrences;
and its termination is based on the fact that if the element is not found it returns -1.
The output of the code is:
Pascal at: 70
O found: 14 times
The second button has code to perform a search and replace one or more elements
of a string with something else. In the first part, it creates a new string copying the
initial and final part and adding some new text in the middle. In the second, it uses
the Replace function that can operate on multiple occurrences simply by passing to
it the proper flag (rfReplaceAll).
This is the code:
// single replace
nIndex := str1.IndexOf ('Pascal');
str1 := str1.Substring(0, nIndex) + 'Object' +
str1.Substring(nIndex + ('Pascal').Length);
Show (str1);

// multi-replace
str1 := str1.Replace('O', 'o', [rfReplaceAll]);
Show (str1);
As the output is rather long and not easy to read, here I've listed only the central
portion of each string:
...Object Pascal ect Object Object...
...Object Object ect Object Object...
...object object ect object object...
Again, this is just a minimal sampler of the rich string operations you can perform
using the operations available for the string type using the string type helper.

More String RTL


An effect of the decision to implement the string helper following the names of oper-
ations common in other programming languages is the fact that the names of the
type operations often diverge from the traditional Object Pascal ones (which are still
available as global functions today.
The following table has some of the not-matching functions names:

Marco Cantù, Object Pascal Handbook


06: All About Strings - 179

global string type helper


Pos IndexOf
IntToStr Parse
StrToInt ToInteger
CharsOf Create
StringReplace Replace

note Remember that there is a big difference between the global and the Char helper operations: The
first group uses a one-based notation for indexing elements within a string, while the latter group
uses a zero-based notation (as explained earlier).

These are only the most commonly used functions of the string RTL that have
changed name, while many others still use the same like UpperCase or QuotedString.
The System.SysUtils unit has a lot more, and the specific System.StrUtils unit
has also many functions focused on string manipulation that are not part of the
string helper.
Some notable functions part of the System.StrUtils unit are:
• ResemblesText, which implements a Soundex algorithm (finding words with sim-
ilar sound even if a different spelling);
• DupeString, which returns the requested number of copies of the given string;
• IfThen, which returns the first string passed if a condition is true, else it will
return the second string (I used this function in a code snippet earlier in this
chapter);
• ReserveString, which returns a string with the opposite characters sequence.

Formatting Strings
While concatenating string with the plus (+) operator and using some of the conver-
sion functions you can indeed build complex strings out of existing values of various
data types, there is a different and more powerful approach to formatting numbers,
currency values, and other strings into a final string. Complex string formatting can
be achieved by calling the Format function, a very traditional but still extremely
common mechanism, not only in Object Pascal but in most programming languages.

note The family of “print format string” or printf functions date back to the early days of program-
ming and languages like FORTRAN 66, PL/1, and ALGOL 68. The specific format string structure
still in use today (and used by Object Pascal) is close to the C language printf function. For a his-
torical overview you can refer to en.wikipedia.org/wiki/Printf_format_string.

Marco Cantù, Object Pascal Handbook


180 - 06: All About Strings

The Format function requires as parameters a string with the basic text and some
placeholders (marked by the % symbol) and an array of values, generally one for
each of the placeholders. For example, to format two numbers into a string you can
write:
Format ('First %d, Second %d', [n1, n2]);
where n1 and n2 are two Integer values. The first placeholder is replaced by the first
value, the second matches the second, and so on. If the output type of the place-
holder (indicated by the letter after the % symbol) doesn't match the type of the
corresponding parameter, a runtime error occurs. Having no compile-time type
checking is actually the biggest drawback of using the Format function. Similarly, not
passing enough parameters causes a runtime error.
The Format function uses an open-array parameter (a parameter that can have an
arbitrary number of values or arbitrary data types, as covered in Chapter 5). Besides
using %d, you can use one of many other placeholders defined by this function and
briefly listed the following table. These placeholders provide a default output for the
given data type. However, you can use further format specifiers to alter the default
output. A width specifier, for example, determines a fixed number of characters in
the output, while a precision specifier indicates the number of decimal digits. For
example,
Format ('%8d', [n1]);
converts the number n1 into an eight-character string, right-aligning the text (use
the minus (-) symbol to specify left-justification) filling it with white spaces. Here is
the list of formatting placeholders for the various data types:
d (decimal) The corresponding integer value is converted to a string of deci-
mal digits.
x (hexadecimal) The corresponding integer value is converted to a string of
hexadecimal digits.
p (pointer) The corresponding pointer value is converted to a string
expressed with hexadecimal digits.
s (string) The corresponding string, character, or PChar (pointer to a
character array) value is copied to the output string.
e (exponential) The corresponding floating-point value is converted to a string
based on scientific notation.
f (floating point) The corresponding floating-point value is converted to a string
based on floating point notation.
g (general) The corresponding floating-point value is converted to the
shortest possible decimal string using either floating-point or
exponential notation.

Marco Cantù, Object Pascal Handbook


06: All About Strings - 181

n (number) The corresponding floating-point value is converted to a float-


ing-point string but also uses thousands separators.
m (money) The corresponding floating-point value is converted to a string
representing a currency amount. The conversion is generally
based on regional settings.
The best way to see examples of these conversions is to experiment with format
strings yourself. To make this easier I've written the FormatString application
project, which allows a user to provide formatting strings for a few predefined inte-
ger values.
The form of the program has an edit box above the buttons, initially holding a sim-
ple predefined formatting string acting as a placeholder ('%d - %d - %d'). The first
button of the application lets you display a more complex sample format string in
the edit box (the code has a simple assignment to the edit text of the format string
'Value %d, Align %4d, Fill %4.4d'). The second button lets you apply the for-
mat string to the predefined values, using the following code:
var
strFmt: string;
n1, n2, n3: Integer;
begin
strFmt := Edit1.Text;
n1 := 8;
n2 := 16;
n3 := 256;

Show (Format ('Format string: %s', [strFmt]));


Show (Format ('Input data: [%d, %d, %d]', [n1, n2, n3]));
Show (Format ('Output: %s', [Format (strFmt, [n1, n2, n3])]));
Show (''); // blank line
end;
If you display the output first with the initial format string and next with the sample
format string (that is if you press the second button, the first, and than the second
again), you should get an output like the following:
Format string: %d - %d - %d
Input data: [8, 16, 256]
Output: 8 - 16 - 256

Format string: Value %d, Align %4d, Fill %4.4d


Input data: [8, 16, 256]
Output: Value 8, Align 16, Fill 0256
However the idea behind the program is to edit the format string and experiment
with it, to see all of the various available formatting options.

Marco Cantù, Object Pascal Handbook

You might also like