pascal中的多个索引数组

时间:2014-08-10 11:38:12

标签: pascal

我在定义多维方面遇到问题

函数ToUpperToLower将资本转换为小。

此代码的主要功能是计算每个字符在输入中出现的次数。只有字母a-z和数字0-9。

VAR
    c: char;
    Counts: Array['0'..'9','a'..'z'] of Integer;
    i : Integer;
Begin
    For c := 'a' to 'z' do
        Counts[c] := 0;
    For c := '0' to '9' do 
        Counts[c] := 0;
    While not EOF do
    Begin
        Read(c);
        c := ToLower(c);
        If ( c >= 'a' ) and ( c <= 'z' ) then 
            Counts[c] := Counts[c] + 1;
        if ( c >= '0' ) and ( c <= '9' ) then
            Counts[c] := Counts[c] + 1;
    end;
    For c := 'a' to 'z' do 
        If Counts[c] <> 0 then
            WriteLn(c,Counts[c]);
end.

1 个答案:

答案 0 :(得分:2)

如果您声明Counts: Array['0'..'9','a'..'z'] of Integer;,则声明一个包含260个元素的数组。 pascal中的多索引数组是一个多维数组,这意味着一个2D矩阵,显然不是你需要的。 您不能声明具有多个索引的一维数组,因此您必须将计数器拆分为2个数组。一个用于计数,另一个用于字母。

代码将是:

var 
  c: char;
  numbers: Array ['0'..'9'] of Integer;
  letters: Array ['a'..'z'] of Integer;
  i : Integer; 

Begin 
  For c := 'a' to 'z' do
    letters[c] := 0;
  For c := '0' to '9' do
    numbers[c] := 0;
  While (not EOF(file)) do 
  Begin
    Read(c);
    c := ToLower(c);
    If ( c >= 'a' ) and ( c <= 'z' ) then 
      letters[c] := letters[c] + 1;
    if ( c >= '0' ) and ( c <= '9' ) then
      numbers[c] := numbers[c] + 1;
  end;
  For c := 'a' to 'z' do 
  begin
    If (letters[c] <> 0) then
      WriteLn(c,Counts[c]);
  end;
  For c := '0' to '9' do 
  begin
    If (letters[c] <> 0) then
      WriteLn(c,letters[c]);
  end;
end.

PS:下次缩进代码,并尝试写一个更清晰的问题。

相关问题