next up previous contents
Next: Homework Assignment (200 points) Up: String Previous: String Length   Contents

Indexing in a String

Although a string is most useful when you treat it as a whole, you can also break it apart, character by character. Indexing into a string is the same as indexing into an array.

Because Pascal was originally designed for beginning programmers, the first character in a string type variable has an index of 1, not 0!

The following code counts the number of spaces in a string:

var
  inputLine : string [80];
  spaceCount : integer;
  i : integer;
begin
  readln(inputLine);
  spaceCount := 0;
  i := 1;
  while i <= length(inputLine) do
    begin
      if inputLine[i] = ' ' then
        spaceCount := spaceCount + 1
    end;
  writeln('the input line has ',spaceCount,' space(s)')
end.



Tak Auyeung 2003-12-03