Since a character can be accessed by index, you can use a variable loop to iterate over all characters, which will take on possible index values. For example, a program that displays all the character codes of the string s would look like this
for i := 1 to length(s) do
writeln(s[i], ord(s[i]))
Explanations for the program:
1) The
length(s)
function finds the length of a string. The index of the first character is 1 and the index of the last is length(s). The loop variable
i will just take values from 1 to length(s).
2) In each line, the symbol itself will be displayed first, and then its code, which is returned by the built-in function
ord()
The same enumeration can be written shorter:
for c in s do
writeln(c, ord(c));
In this fragment, the loop header loops through all the characters s, placing them in turn in the variable c.
The peculiarity of Pascal when working with strings is that strings are mutable objects. In other words, we can change individual characters of a string.
For example, the following statement will work
s[5] := 'a';
You can also compose a new string from the characters with the required changes.
For example, a program that replaces all characters 'a' to characters 'b' will look like this:
read(s);
for i := 1 to length(s) do begin
if s[i] = 'a'then s[i] := 'b';
end;
writeln(s);
In this example, we loop through all the characters of the string s. In the body of the loop, we check the value of the variable s[i]: if the character matches the character 'a', then we replace it with 'b'.