Maybe you already know what is a string variable from previous program examples that you have tried, but you don't know what operations and what functions one can apply to them and how can they be manipulated in order to obtain another form of string whatsoever.
In this lesson we will cover some important functions that the Pascal programming language has for us in order to cater for string operations far more easier to use than you think.
Let's jump into the strings staff straight away. In order to understand strings, one has to keep in mind that a string is made up of an array of characters. The string data type is an in-built data type that is an array of 256 characters (Type String = Packed Array[0..255] of Char). When stored in memory, the processor should know where the string starts and where it finishes. In order to know where the string finishes, in Pascal, the 0th element of a string is defined as the length of the string. So, if you try to access character 0 of a string, the number of characters stored in that array is returned, thus letting the processor to know where the string finishes.
The following example shows some simple string operations.
Var
myString : String;
Begin
myString := 'Hey! How are you?';
Writeln('The length of the string is ',byte(myString[0]));
Write(myString[byte(myString[0])]);
Write(' is the last character.');
End.
|
Note that in the previous program I have used an automatic data-type conversion, normally referred to as data type-casting. When type-casting from one data type to another, all that is happening is simply a conversion from one data type to another based on the data type in subject and the wrapping data type to which the old data type is being converted. In our case, the array variable myString has a special 0th element storing the number of characters in that array in string format. This value is an ascii value, so trying to display it without converting it into a number, the alternative ascii character is displayed. So you have to change the character value to an ordinary number by wrapping the variable by another data type, in our case a byte data type (why use integer? - its all waste of memory and memory consumption).
Note that myString[myString[0]] without having data-type casting around myString[0] will lead to a compiler error because myString[0] is a character and not an integer.
Note that to retrieve the length of a string (ie. the number of characters in a string) there is no need to use the method I showed to you because its too complicated and unfriendly. Instead, there is the simpler function, length() which will return the number of characters of the string in subject. Eg. numOfChars := length(myString);

|