delphi – How do I convert a non-null-terminated char array into a string? – Education Career Blog

I have a function that takes in a pointer to a series of char.
I wish to copy 256 chars from that point, and place them in a string.

msg is not null-terminated.

The below code seems to give me some problem.
Is there a correct way to do this?

Init( msg: PCHAR)
var
 myStr: String;
begin
 for i:= 1 to 256 do
 begin
  myStri := msgi-1; 
 end;
end;

,

SetString(myStr, msg, 256);

,

Your code misses SetLength, the corrected version is:

Init( msg: PCHAR)
var
 myStr: String;
begin
 SetLength(myStr, 256);
 for i:= 1 to 256 do
 begin
  myStri := msgi-1; 
 end;
end;

The assignment can be done more efficiently as already answered.

Updated

SetLength allocates 256 characters + terminating 0 for myStr; without SetLength your code is an error: it writes to wild address and will finally result in access violation.

,

If msg is null-terminated, as it should be, and the 256 characters you want to obtain are followed by the null character, simply do

myStr := msg;

If msg is longer than that, you could just do

myStr := Copy(msg, 1, 256);

In this case, a better method is

myStr := WideCharLenToString(msg, 256);

assuming you are using Delphi 2009 or later, in which the strings are Unicode.

,

myStr := Copy(msg, 1, 256);

Leave a Comment