我问过类似的question https://stackoverflow.com/questions/17580662/how-to-read-a-text-file-that-contains-null-character-in-delphi几个月前。谢谢罗布·肯尼迪 https://stackoverflow.com/users/33732/rob-kennedy我可以将整个文本加载到Richedit
但我无法删除Null chars
.我可以加载我的文本,因为我使用了Stream
.
现在在这段代码中:
var
strm : TMemorystream;
str : UTF8string;
ss : TStringstream;
begin
strm := tmemorystream.Create;
try
strm.LoadFromFile('C:\Text.txt');
setstring(str,PAnsichar(strm.Memory),strm.Size);
str := StringReplace(str, #0, '', [rfReplaceAll]); //This line doesn't work at all
ss := tstringstream.Create(str);
Richedit1.Lines.LoadFromStream(ss);
finally
strm.Free;
ss.Free;
end;
end;
我转换了TMemorystream
to string
去除Null Chars
with StringReplace()
然后再次将其转换为TStringstream
加载它Richedit.lines.LoadFromStream
.
但我的问题是无法删除Null Character
using StringReplace()
。我可以替换其他角色,但不行#0
.
有没有办法直接删除空字符TMemorystream
并将其加载到Richedit
?如何?如果不可能或者非常复杂,当我将文本转换为string
?
Thanks.
Sertac的答案是准确的,你应该接受它。如果性能很重要,并且您有一个大字符串,并且频繁出现空字符,那么您应该尝试减少堆分配的数量。以下是我将如何实现这一点:
function RemoveNull(const Input: string): string;
var
OutputLen, Index: Integer;
C: Char;
begin
SetLength(Result, Length(Input));
OutputLen := 0;
for Index := 1 to Length(Input) do
begin
C := Input[Index];
if C <> #0 then
begin
inc(OutputLen);
Result[OutputLen] := C;
end;
end;
SetLength(Result, OutputLen);
end;
如果你想直接在内存流中执行,那么你可以这样做:
procedure RemoveNullFromMemoryStream(Stream: TMemoryStream);
var
i: Integer;
pIn, pOut: PByte;
begin
pIn := Stream.Memory;
pOut := pIn;
for i := 0 to Stream.Size-1 do
begin
if pIn^ <> 0 then
begin
pOut^ := pIn^;
inc(pOut);
end;
inc(pIn);
end;
Stream.SetSize(NativeUInt(pOut)-NativeUInt(Stream.Memory));
end;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)