Pascal Programming/Strings

From Wikibooks, open books for an open world
< Pascal Programming
Jump to: navigation, search

String is just an array of ASCII characters.


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;
  s:='This is a example of string';

The output:


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)


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}