开发者

How do I convert a non-null-terminated char array into a string?

开发者 https://www.devze.com 2023-01-21 03:13 出处:网络
I have a function that takes in a pointer to a series of char. I wish to copy 256 chars from that point, a开发者_Go百科nd place them in a string.

I have a function that takes in a pointer to a series of char. I wish to copy 256 chars from that point, a开发者_Go百科nd 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
  myStr[i] := msg[i-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
  myStr[i] := msg[i-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);

0

精彩评论

暂无评论...
验证码 换一张
取 消