Ian Boyd
Ian Boyd

Reputation: 256731

How to access characters of a WideString by index?

i have the following code snippit that won't compile:

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;

Delphi5 complains Incompatible types.

i tried simplifying it down to:

s := Grob[7]; 

which works, and:

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

which does not.

i can only assume that WideString[index] does not return a WideChar.

i tried forcing things to be WideChars:

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

But that also fails:

Incompatible types

Footnotes

Upvotes: 4

Views: 1513

Answers (3)

Arnaud Bouchez
Arnaud Bouchez

Reputation: 43033

The easier, and faster, in your case, is the following code:

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;

Using a WideString(Grob[7])+WideString(Grob[8]) expression will work (it circumvent the Delphi 5 bug by which you can't make a WideString from a concatenation of WideChars), but is much slower.

Creation of a WideString is very slow: it does not use the Delphi memory allocator, but the BSTR memory allocator supplied by Windows (for OLE), which is damn slow.

Upvotes: 10

Ian Boyd
Ian Boyd

Reputation: 256731

As Geoff pointed out my other question dealing with WideString weirdness in Delphi, i randomly tried my solution from there:

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;

And it works. Delphi is confused about what type a WideString[index] in, so i have to beat it over the head.

Upvotes: 4

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108963

Grob[7] is a WideChar; that's not the issue.

The issue seems to be that the + operator cannot act on wide chars. But it can act on wide strings, and any wide char can be cast to a wide string:

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

Upvotes: 7

Related Questions