无法从字符串中删除`Null Characters` [英] Cannot remove `Null Characters` from a string
问题描述
我问过类似的问题几个月前。感谢 Rob Kennedy 我可以将我的整个文字载入 Richedit
但我无法删除 Null chars
。我可以加载我的文本,因为我使用 Stream
。
I asked a similar question couple months ago. Thanks to Rob Kennedy I could load my whole text into a Richedit
BUT I couldn't remove Null chars
. I could load my text because I used 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
转换为 string
使用 StringReplace()
删除 Null Chars
TStringstream
加载 Richedit.lines.LoadFromStream
。
I converted TMemorystream
to string
to remove Null Chars
with StringReplace()
and then converted it again to TStringstream
to load it with Richedit.lines.LoadFromStream
.
但我的问题是,我不能删除空字符
使用 StringReplace()
。我可以替换其他字符,但不能替换#0
。
But my problem is that I can't remove Null Character
using StringReplace()
. I can replace other characters but not #0
.
c $ c> TMemorystream 并将其加载到 Richedit
中?怎么样?如果不可能或非常复杂,当我将文本转换为 string
?时,如何删除它们?
Is there any way to remove null charcters directly in TMemorystream
and load it into a Richedit
? How? If it's not possible or it's very complex, how can I remove them when I convert my text to string
?
感谢。
推荐答案
据我所见,所有搜索/替换实用程序, PChar,其中'#0'是终止字符。因此,它们不会超过第一个Null之前的字符串部分。你可能需要设计自己的机制。只是一个快速示例:
As far as I can see, all searching/replacing utilities, at one time or other, cast the input to a PChar, which '#0' is the termination character. Hence they never go past the string part that's before the first Null. You may need to devise your own mechanism. Just a quick example:
var
i: Integer;
begin
Assert(str <> '');
i := 1;
while i <= Length(str) do
if str[i] = #0 then
Delete(str, i, 1)
else
Inc(i);
在流中替换将类似地包括测试每个字符,然后在移动之前相应地调整流决定删除一个。
Replacing in the stream would similarly involve testing each character and then adjusting the stream accordingly before moving on after you decide to delete one.
这篇关于无法从字符串中删除`Null Characters`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!