15

I want to copy the content in the string to char array.

Can I use this code StrLCopy(C, pChar(@S[1]), high(C));

I am currently using Delphi 2006. Will there be any problems if I upgrade my Delphi version because of Unicode support provided in newer versions?

If not, what can be the code for this conversion?

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
Bharat
  • 6,828
  • 5
  • 35
  • 56

2 Answers2

17

When you're copying a string into an array, prefer StrPLCopy.

StrPLCopy(C, S, High(C));

That will work in all versions of Delphi, even when Unicode is in effect. The character types of C and S should be the same; don't try to use that function to convert between Ansi and Unicode characters.

But StrLCopy is fine, too. You don't need to have so much pointer code, though. Delphi already knows how to convert a string into a PChar:

StrLCopy(C, PChar(S), High(C));
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
7

This works, in a quick test:

var
  ch: array[0..10] of Char;
  c: Char;
  x: Integer;
  st: string;
begin
  s := 'Testing';
  StrLCopy(PChar(@ch[0]), PChar(s), High(ch));
  x := 100;
  for c in ch do
  begin
    Canvas.TextOut(x, 100, c);
    Inc(c, Canvas.TextWidth(c) + 3);
  end;
end;
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • Can you please tell me the difference between the two STrlCopy statements – Bharat Dec 14 '10 at 15:47
  • Thank you Ken for taking time – Bharat Dec 14 '10 at 15:56
  • The help says: "Warning: The ANSI version of StrLCopy is deprecated. Please use the AnsiStrings unit." – Gabriel Mar 27 '21 at 14:46
  • This answer was written more than a decade ago, and the procedure was not deprecated at that time. If you're getting that waning, then add the AnsiStrings unit to your implementation `uses` clause to stop it. Out of curiosity, why did you choose to comment on my answer instead of the other one, or the question itself? – Ken White Mar 27 '21 at 14:59