< Pascal Programming

String is just an array of ASCII characters.

Definition

string type is defined like this:

 type string = packed array [0..255] of char;

Consider this code:

 program string_sample;
 uses crt;
 var s: string;
     i: longint;
 begin
  s:='This is an example of string';
  writeln(s[1]);
  writeln(ord(s[0]));
  readln;
 end.

The output:

T
27

We can see that:

  • Because strings are just an ASCII array, we can access to any character in string just like array (s[1] in the example above will return the character T)
  • What is the purpose of s[0]? s[0] stores the length of the string s but the length is not stored as a number, it is stored as the ASCII character of the length. For example, if string s has the length of 65, s[0] will return the character A, because the ASCII number of A is 65. And the first character of the string is stored in s[1]. So a string can only store up to 255 characters. But don't use this method to retrieve the length of a string because there is a function that can do that (see below)

Declare

Just like longint or integer:

 var s: string;

In the above example, string s can store up to 255 characters.

But what if you want the string s to store up to 10 characters?

 var s: string[10]; {OK, so now s can only store up to 10 chars}
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.