从Delphi 2006中的WideString中删除空字符 [英] Remove null characters from WideString in Delphi 2006

查看:146
本文介绍了从Delphi 2006中的WideString中删除空字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些数据的WideString变量,但是当字符串被分配了一些额外的空值,这些值在数据中的随机位置或多或少地添加。我现在需要从变量中删除这些空值。如果它是一个字符串,我将检查每个Char,以查看Char(x)= 0,但是因为这是一个WideString我不认为这个工作?我如何最好地剥离这些?



我使用的是Delphi 2006

解决方案>

你看到的内容可能不是空字符。它们可能只是一个字符的高八位,代码点值小于256。



如果您确实在字符串中有空字符,应该在那里,你应该做的第一件事是弄清楚他们如何到达那里。如果他们不在那里,那么程序中可能有一个错误。



如果生成该字符串的代码是无bug的,而且还有不必要的空字符,那么你可以很容易地删除它们。从字符串中删除内容的常见方法是使用 删除 标准功能。您可以使用语法通过其数值指定任何字符,编译器通常可以确定是否需要表示AnsiChar或WideChar。

  procedure RemoveNullCharacters(var s:WideString); 
var
i:整数;
begin
i:= 1;
,而i<如果s [i] =#0,那么
删除(s,i,1)
else
Inc(i);
结束

但是可能会重新分配字符串多次(每个空字符一次)。为了避免这种情况,您可以将字符串放在原位:

  procedure RemoveNullCharacters(var s:WideString); 
var
i,j:整数;
begin
j:= 0;
for i:= 1 to Length(s)do
如果s [i]<> #0然后开始
Inc(j);
s [j]:= s [i];
结束
如果j < Length(s)then
SetLength(s,j);
结束

这些功能适用于任何Delphi的字符串类型;只需更改参数类型。


I have a WideString variable containing some data but when the string was assigned some extra nulls where added at more or less random places in the data. I now need to strip these nulls out of the variable. If it had been a string I would have checked each Char to see if Char(x) = 0 but as this is a WideString I dont think this work? How can I best strip these out?

I'm using Delphi 2006

解决方案

What you're seeing probably aren't null characters. They're probably just the upper eight bits of a character with a code-point value less than 256.

If you really do have null characters in your string that aren't supposed to be there, the first thing you should do is figure out how they're getting there. There's probably a bug in your program if they're there when they shouldn't be.

If the code that generates the string is bug-free and you still have unwanted null characters, then you can remove them fairly easily. The common way to remove stuff from a string is with the Delete standard function. You can specify any character by its numeric value with the # syntax, and the compiler can usually figure out whether it needs to represent an AnsiChar or a WideChar.

procedure RemoveNullCharacters(var s: WideString);
var
  i: Integer;
begin
  i := 1;
  while i < Length(s) do
    if s[i] = #0 then
      Delete(s, i, 1)
    else
      Inc(i);
end;

But that may re-allocate the string many times (once for each null character). To avoid that, you can pack the string in-place:

procedure RemoveNullCharacters(var s: WideString);
var
  i, j: Integer;
begin
  j := 0;
  for i := 1 to Length(s) do
    if s[i] <> #0 then begin
      Inc(j);
      s[j] := s[i];
    end;
  if j < Length(s) then
    SetLength(s, j);
end;

Those functions will work for any of Delphi's string types; just change the parameter type.

这篇关于从Delphi 2006中的WideString中删除空字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆