【问题标题】:How to Split string by SplitString or delimiter?如何通过分隔符上的拆分字符串拆分字符串?
【发布时间】:2017-02-05 19:09:37
【问题描述】:

我有客户端和服务器应用程序。 我在双方都使用 App tethering。 在服务器端,我有 SQLite 数据库 在客户端没有数据库; 客户端从服务器数据库获取数据。 使用服务器代码,我认为没问题。客户有问题,我不能拆分!!!我在 Client Side 上写了代码。谁能告诉我,我的错误在哪里??? 如何拆分 r3.Text:=AResource.Value.AsString; ?

服务器端代码:

procedure TfServerPage.tAProfileResourceReceived(const Sender: TObject;
  const AResource: TRemoteResource);
  var
    result:string;
    r1,r2,r3:TstringList;
  begin

if AResource.Hint='List' then
        begin
          //ShowMessage(AResource.Value.AsString);
            r1:=TStringList.Create;
            r2:=TStringList.Create;
            r3:=TStringList.Create;
            rQuery.Open;
             while not rQuery.Eof do
                begin
                 r1.add(rQuery.FieldByName('username').AsString);
                 r2.add(rQuery.FieldByName('password').AsString);
                 r3.add(rQuery.FieldByName('nickname').AsString);
                 rQuery.Next;
                end;
            result:=r1.Text+#13+r2.Text+#13+r3.text;
           tAProfile.SendString(tManager.RemoteProfiles.First,'List2',result);

        end;
end;

客户端代码:

procedure TfAuth.tAProfileResourceReceived(const Sender: TObject;
  const AResource: TRemoteResource);
var i:integer;
r3,s1,s2,s3:TStringList;
begin


    if AResource.Hint='List2' then
      begin
        r3:=TStringList.Create;
        r3.Text:=AResource.Value.AsString;    // <-From Server

        s1:=TStringList.Create;
        s2:=TStringList.Create;
        s3:=TStringList.Create;

      s1.Text:=SplitString(r3.Text,#13)[0]; //Split username
      s2.Text:=SplitString(r3.Text,#13)[1]; //password
      s3.Text:=SplitString(r3.Text,#13)[2]; //nickname

       for i := 0 to r3.Count do
           begin
            StringGrid1.Cells[0,i]:=s1[i];   
            StringGrid1.Cells[1,i]:=s2[i];  
            StringGrid1.Cells[2,i]:=s3[i]; 
           end;
    end;

end;

【问题讨论】:

  • 我认为你应该写s1.Add (SplitString(r3.Text,#13)[0] ); 而不是s1.Text:=SplitString(r3.Text,#13)[0];`

标签: delphi


【解决方案1】:

在服务器端,您将 db 记录中的字段添加到 3 个字符串列表中,r1 - 用户名,r2 - 密码和 r3 - 昵称。字符串列表默认使用 CarriageReturn - LineFeed(或 #13#10)作为行尾字符。

当您将这些字符串列表的文本与 r1.Text、r2.Text 和 r3.Text 之间的 #13 连接时,根据 #13 拆分回字符串列表会出错。您应该使用其他字符作为字符串列表的分隔符。尝试例如#11(垂直标签)。

我也会在客户端只使用s:string 而不是r3:TStringList。

你正在泄漏内存,应该释放TStringList的!

不过,如果您要传输更大的数据记录,您应该考虑使用 XML 或 JSON。这些提供了以更方便的方式序列化数据的方法。

【讨论】:

  • 兄弟,在我的情况下如何使用 JSON...? ;((((
  • 抱歉,Alex,但这是一个太宽泛的话题,无法在 Stack Overflow 上回答。初学者可以在帮助和示例中查看“delphi json”等。网上有很多文档和文章。
【解决方案2】:

服务器端代码:

 result:=r1.Text+#0+r2.Text+#0+r3.text;

客户端代码:

 s1.Text:=SplitString(r3.Text,#0)[0];

  s2.Text:=SplitString(r3.Text,#0)[1];

  s3.Text:=SplitString(r3.Text,#0)[2];

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 2014-03-02
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2018-05-05
    • 2011-03-29
    • 1970-01-01
    相关资源
    最近更新 更多