如何按索引访问宽字符串的字符



我有以下代码截图无法编译:

procedure Frob(const Grob: WideString);
var
   s: WideString;
begin
   s := 
       Grob[7]+Grob[8]+Grob[5]+Grob[6]+Grob[3]+Grob[4]+Grob[1]+Grob[2];
   ...
end;

德尔福5抱怨Incompatible types .

我尝试将其简化为:

s := Grob[7]; 

哪个有效,并且:

s := Grob[7]+Grob[8];

哪个没有。

我只能假设WideString[index]不返回WideChar.

我试着强迫事情变得WideChars

s := WideChar(Grob[7])+WideChar(Grob[8]);

但这也失败了:

不兼容的类型

脚注

  • 5 : 德尔福 5
在您

的情况下,以下代码更简单、更快捷:

procedure Frob(const Grob: WideString);
var
   s: WideString;
begin
  SetLength(s,8);
  s[1] := Grob[7];
  s[2] := Grob[8];
  s[3] := Grob[5];
  s[4] := Grob[6];
  s[5] := Grob[3];
  s[6] := Grob[4];
  s[7] := Grob[1];
  s[8] := Grob[2];
   ...
end;

使用WideString(Grob[7])+WideString(Grob[8])表达式将起作用(它绕过了 Delphi 5 错误,您无法通过 WideChars 的串联进行WideString),但速度要慢得多。

创建WideString非常慢:它不使用Delphi内存分配器,而是Windows(用于OLE)提供的BSTR内存分配器,这非常慢。

Grob[7]是一个WideChar;这不是问题所在。

问题似乎是+运算符无法对宽字符进行操作。但它可以作用于宽字符串,任何宽字符都可以转换为宽字符串:

S := WideString(Grob[7]) + WideString(Grob[8]);

当Geoff指出我的另一个问题时,我从那里随机尝试了我的解决方案:

procedure Frob(const Grob: WideString);
var
   s: WideString;
const
   n: WideString = ''; //n=nothing
begin
   s := 
      n+Grob[7]+Grob[8]+Grob[5]+Grob[6]+Grob[3]+Grob[4]+Grob[1]+Grob[2];
end;

它有效。德尔菲对WideString[index]的是什么类型感到困惑,所以我不得不把它打在头上。

最新更新