How to declare strings in Pascal

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.

String length

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.

Accessing characters of a string

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.

Examples

Example 1

Consider the code snippet below, which demonstrates the declaration of string:

program stringExample1;
var
str: String = 'Hello world';
begin
writeln(str);
end.

Example 2

Consider the code snippet below, which calculates the length of a string and prints its first and last character:

program stringExample2;
var
str: String = 'Hello world';
begin
writeln('String length = ', byte(str[0]));
writeln('First character in str = ', str[1]);
writeln('Last character in str = ', str[byte(str[0])]);
end.

Explanation

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

Copyright ©2024 Educative, Inc. All rights reserved