What you think is the text of the file isn't really the text of the file. What you've read into your string variable is accurate. You have a Unicode text file encoded as little-endian UTF-16. The first two bytes represent the byte-order mark, and each pair of bytes after that are another character of the string.
If you're reading a Unicode file, you should use a Unicode data type, such as WideString
. You'll want to divide the file size by two when setting the length of the string, and you'll want to discard the first two bytes.
If you don't know what kind of file you're reading, then you need to read the first two or three bytes first. If the first two bytes are $ff $fe, as above, then you might have a little-endian UTF-16 file; read the rest of the file into a WideString
, or UnicodeString
if you have that type. If they're $fe $ff, then it might be big-endian; read the remainder of the file into a WideString
and then swap the order of each pair of bytes. If the first two bytes are $ef $bb, then check the third byte. If it's $bf, then they are probably the UTF-8 byte-order mark. Discard all three and read the rest of the file into an AnsiString
or an array of bytes, and then use a function like UTF8Decode
to convert it into a WideString
.
Once you have your data in a WideString
, the debugger will show that it contains version
, and you should have no trouble using a Unicode-enabled version of StringReplace
to do your replacement.