Pascal Made Simple by P K McBride

Pascal Made Simple by P K McBride

Author:P K McBride [McBride, P K]
Language: eng
Format: mobi
Published: 2011-06-14T16:00:00+00:00


Comparing strings

In Turbo Pascal, comparing strings is no problem. In standard Pascal there is a problem, as you cannot compare arrays. The solution is to write a function to do the job for you.

The code for this is straightforward. It loops through both strings in tandem until it finds two characters that are different, or reaches the end of the shortest string. We could do this with the line:

while (s1[loop] = s2[loop]) and (loop <= length(s1)) and (loop <= length(s2) do

That is not a nice line! A neater solution is to find the length of the shortest string first:

if length(s1) < length(s2)

then size := length(s1)

else size := length(s2);

That allows us to use the clearer control line:

while (s1[loop] = s2[loop]) and (loop <= size) do

The return value is then determined by comparing the characters at the loop position, and is 1 if s1 is more than s2, –1 if it is less and 0 if the two are the same.

if s1[loop] > s2[loop]

then strcomp := 1

else if s1[loop] < s2[loop]

then strcomp := -1

else strcomp := 0;

This works even when the end of a string has been reached, as the next character in the shorter string will be 0, the terminator, and this is bound to be less than anything in the other string.

Take note

You must include the stringin, stringout and length procedures for this to work.

String comparison

program stringcomp;

type

string80 = packed array [1..80] of char;

var

words1 : string80;

words2 : string80;

ans : integer;

{include procedure stringout , stringin, length}

function strcomp(s1,s2:string80):integer;

var

loop : integer;

size : integer;

begin

if length(s1) < length(s2)

then size := length(s1)

else size := length(s2);

{FInd the shortest string and set size to this value.}

loop := 1;

{Loop through them both.}

while (s1[loop] = s2[loop]) and (loop <= size) do

loop := loop + 1;

{Compare the characters at the end of the loop.}

if s1[loop] > s2[loop]

then strcomp := 1

else if s1[loop] < s2[loop]

then strcomp := -1

else strcomp := 0;

end;

begin

writeln(‘Enter first item: ’);

stringin(words1);

writeln(‘Enter next item: ’);

stringin(words2);

ans := strcomp(words1,words2);

if ans = 1 then writeln(‘First larger’)

else if ans = 0 then writeln(‘Equal’)

else writeln(‘Second larger’);

end.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.