String
is a built-in data type in Pascal used to store a sequence of characters. The declaration of String
in Pascal is shown below:
_variableName_ : String = _stringBody_;
_variableName_
: The variable name that identifies the variable._stringBody_
: The body of the string which is a sequence of characters. The body of the string is enclosed in single quotes.The length of a string is the number of characters stored in it. The string length in Pascal is calculated as shown below:
length := byte(str[0]);
The code snippet above stores the string length of str
in length
.
To access a character of a string, use the []
operator, as shown below:
character = str[ind];
The code snippet above stores the character at the index ind
in str
in character
.
Consider the code snippet below, which demonstrates the declaration of string
:
program stringExample1;varstr: String = 'Hello world';beginwriteln(str);end.
Consider the code snippet below, which calculates the length of a string and prints its first and last character:
program stringExample2;varstr: String = 'Hello world';beginwriteln('String length = ', byte(str[0]));writeln('First character in str = ', str[1]);writeln('Last character in str = ', str[byte(str[0])]);end.
byte(str[0])
is the number of characters in str
. As str[ind]
is used to print the character of str
at index ind
, str[1]
will print the first index of str
. str[byte(str[0])]
prints the character at the last index, as byte(str[0])
is equal to the length of str
.
Free Resources