[fpc-pascal] Concatenating CP Strings

Sven Barth pascaldragon at googlemail.com
Sun Sep 16 12:49:48 CEST 2018

On 9/15/18 1:38 AM, Martok wrote:
> Hi all,
> concatenating codepage strings is documented to be a bit weird:
> <http://wiki.freepascal.org/FPC_Unicode_support#String_concatenations>
> Knowing this, how does one achieve the following?
> - have a string in any dynamic codepage
> - append another string (possibly from different CP), or a literal
> - have the result in the same dynamic codepage as before
> Literally, "transcode the new part and plop it at the end"?
> Using AnsiStrings does not work, as the declared CP is CP_ACP, which is not the
> dynamic CP, and loss of data is likely. Using RawByteStrings does not work, as
> they get converted to CP_ACP regardless of their current dynamic CP, and loss of
> data is likely. Insert() does not work, because it doesn't care about characters
> at all and just moves bytes.
> Doing the entire thing manually with a temp string does work, but such a simple
> task can't be that difficult, can it?

Safest and cleanest would probably be something like this:

=== code begin ===

function ConcatWithCP(const aLeft, aRight: RawByteString; aCP: LongInt):
RawByteString; inline;
  Result := aLeft;
  SetCodePage(Result, CP_UTF8, True);
  Result := Result + aRight;
  SetCodePage(Result, aCP, True);

=== code end ===

(alternatively with an array of RawByteString to concatenate multiple
strings at once)


More information about the fpc-pascal mailing list