Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying string content to char array

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?

like image 871
Bharat Avatar asked Dec 14 '10 14:12

Bharat


People also ask

How do I copy a string into a character array?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.

Does strcpy work with arrays?

strcpy can be used to copy one string to another. Remember that C strings are character arrays. You must pass character array, or pointer to character array to this function where string will be copied. The destination character array is the first parameter to strcpy .

How do I convert a single string to a char in C++?

you can't convert a string to a char you will have to convert it to char array. if you want to grab a single character from a string you can do it by putting index of the character like data[index] and assign it to character variable.


2 Answers

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));
like image 158
Rob Kennedy Avatar answered Sep 30 '22 09:09

Rob Kennedy


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;
like image 32
Ken White Avatar answered Sep 30 '22 09:09

Ken White