Link to home
Start Free TrialLog in
Avatar of qanuj
qanujFlag for India

asked on

How to Remove #0 Char : Delphi

I have a string variable with "nul" ie. #0 char repeatedly coming up. How can i remove all #0 Chars.
Avatar of qanuj
qanuj
Flag of India image

ASKER

May be Adding more points would help
Avatar of dinilud
Can you explain more.
ASKER CERTIFIED SOLUTION
Avatar of ZhaawZ
ZhaawZ
Flag of Latvia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Another alternative

Regards,
Russell

-----

example usage:

var  S:             String;
begin

  S:=#0'Hello'#0#0' World'#0' this is a test'#0;
  RemoveChar(S, #0);
  Edit1.Text:=S;

end;

// Procedure to remove a specified char from a string variable
procedure RemoveChar(var S: String; Ch: Char);
var  dwShift:       Integer;
     dwIndex:       Integer;
begin

  // Check string length
  if (Length(S) > 0) then
  begin
     // Set shift
     dwShift:=0;
     // Walk the string
     for dwIndex:=1 to Length(S) do
     begin
        // Check for char
        if (S[dwIndex] = Ch) then
           // Increment the shift
           Inc(dwShift)
        // Determine if shift is in effect, if not then no move needs to be done
        else if (dwShift > 0) then
           // Move char to shifted position
           S[dwIndex - dwShift]:=S[dwIndex];
     end;
     // Check for total shift, update string length if required
     if (dwShift > 0) then SetLength(S, Length(S) - dwShift);
  end;

end;
Avatar of JeePeeTee
JeePeeTee

Shorty:

procedure RemoveChar(var S: String; Ch: Char);
var
  I:Integer;
begin
  if Length(S) = 0 then
    Exit;

  for I := (Length(S) - 1) downto 0 do begin
    if (S[I] = Ch) then
      Delete(S, I, 1);
  end;
end;
i prepose rllibby's solution
When iterating through data and removing some I prefer to work from end-to-begin instead of begin-to-end.
Try this

Function RemoveNull(var str : string):string;
var
  i:integer;
  temp:string;
begin
  if length(str)>0 then
  begin
    for i:=1 to length(str) do
    if str[i]<>#0 then temp:=temp+str[i];
    RemoveNull:=temp;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  s : string;
begin
  s := 'one'#0'two'#0'three';
  ShowMessage(RemoveNull(s));
end;
Or even shorter...

function RemoveNull(AString: string) : string
 var s : string;
begin
  s := AString;
  while Pos(s, #0) > 0 then
    Delete(s, Pos(s, #0), 1);

  result := s;
end;