Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

string - Delphi Pos always returning 0

I really don't know why Pos keep returning 0 instead of the char ";" position in string I have to get a response of a php page which outputs a Content-Type: text/plain So one example output is 2;fulano;fulano;0 3;ciclano;ciclano;0 4;beltrano;beltrano;0 5;foo;foo;0 8;jose;jose;0 9;maria;maria;0

and the code is

var
  linha,uid,login,senha,email,tipo : WideString;
  resposta : TStringList;
  I : Integer;
begin
  try
    resposta := TStringList.Create;
    resposta.Text := frmMain.IdHTTP1.Get(frmMain.cdsConfig.FieldByName('WebService').AsString+'listdest.php');
    for I := 0 to resposta.Count-1 do
    begin
      linha := resposta.Strings[i];
      if i = 0 then
        Delete(linha,1,1); // the first line have one wierd $FEFF
      if length(linha) > 5 then
        begin

          uid := Copy(linha,1,Pos(linha,';')-1);
          Delete(linha,1,Pos(linha,';'));
          login:=Copy(linha,1,Pos(linha,';')-1);
          Delete(linha,1,Pos(linha,';'));
          senha:=Copy(linha,1,Pos(linha,';')-1);
          Delete(linha,1,Pos(linha,';'));
          email:=Copy(linha,1,Pos(linha,';')-1);
          Delete(linha,1,Pos(linha,';'));
          tipo:=Copy(linha,1,Pos(linha,';')-1);
          Delete(linha,1,Pos(linha,';'));
        end;
    end;
    //dlgWait.Close;
  except on E :Exception do
    begin
      MessageBox(Self.Handle,PWideChar(E.Message),'Erro',MB_OK+MB_ICONERROR+MB_APPLMODAL);
      dlgWait.Close;
      FreeAndNil(resposta);
    end;
  end;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your call to Pos is backwards. The parameters are:

function Pos(const SubStr, Str: _ShortStr; Offset: Integer): Integer;

But your code assumes they are:

function Pos(const Str, SubStr: _ShortStr; Offset: Integer): Integer;

So actually what it's trying to do is look for the value of linha within ';', which of course unless linha = ';', it will return 0.

Another way to put it, as Rudy said, instead of looking for a needle in a haystack, your code is looking for a haystack in a needle.

Swap around the first and second parameters to these calls.


On a side note, just a tip for performance. Rather than calling Pos twice for each, keep a cached copy of the value...

P := Pos(';', linha);
uid := Copy(linha,1,P-1);
Delete(linha,1,P);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...