Delphi的字符处理
(一)字符类型
字符类型是一个有序类型,字符的大小顺序按其ASCII代码的大小而定。函数Succ、Pred、Ord适用于字符类型。
例如:
后继函数:Succ('a')='b';
前继函数:Pred('B')='A';
序号函数:Ord('A')=65;
例1:按字母表顺序和逆序每隔一个字母打印。即打印出:
a c e g i k m o q s u w y
z x r v t p n l j h f d b
程序如下:
program ex8_1;
var
letter:char;
begin
for letter:='a' to 'z' do
if(Ord(letter)-Ord('a')) mod 2=0 then write(letter:3);
writeln;
for letter:='z'' down to 'a' do
if(Ord(letter)-Ord('z')) mod 2 =0 then write(letter:3);
writeln;
end;
(二)字符串类型
type<字符串类型标识服>=string[n]
其中:n是定义的字符串长度,必须是0~255之间的 自然整数,第0号单元中存放字符串的实际长度,
程序运行时由系统自动提供,第1~n号单元中存放字符串。若将string【n】写成string,则默认n为255
例:
求输入英文句子单词的平均长度
程序如下:
program ex8_2;
var
ch:string;
s,count,j:integer;
begin
write('The sentence is:');
readln(ch)
s:=0;
count:=0;
j:=0;
repeat
inc(j);
if not(ch[j] in [':', ',', ';', '!', '?', '.', ' '] then inc(s);
if ch[j] in [' ', ',', '.', '!', '?'] then inc(count);
unntil (j=Ord (ch[0])) or (ch[j] in['.', '!', '?']);
if ch[j]<>'.' then writeln('it is not a sentence.')
else whriteln('Average length is 's/count:10:4);
end;