【问题标题】:How do I combine multiple values into a single string?如何将多个值组合成一个字符串?
【发布时间】:2013-12-01 18:45:35
【问题描述】:

我正在努力学习 Delphi,目前正在制作游戏。我以前对Pascal有点了解,但对Delphi一无所知。几年前我用 Pascal 制作了这个游戏。它包含这样的一行:

writeln(turn,'  ',input,'   ',die[turn],'  ',wou[turn]);

基本上它是为了显示用户输入的计算结果,这些数字之间有几个空格(所有这些变量都是数字,除了“输入”,它是一个字符串)。

我正在尝试在 Delphi 中类似地显示结果。虽然最好使用表格,但我不知道如何使用表格,所以我尝试使用列表框。但是 items.add 过程不像 Pascal 的 writeln 那样工作,因此我目前被卡住了。

我是新人,第一次学习,所以请让我容易理解。

【问题讨论】:

    标签: delphi listbox


    【解决方案1】:

    使用Format 函数,来自SysUtils 单元。它返回一个字符串,您可以在任何可以使用字符串的地方使用该字符串:

    // Given these values for turn, input, die[turn], and wou[turn]
    turn := 1;
    input := 'Whatever';
    die[turn] := 0;
    wou[turn] := 3;
    
    procedure TForm1.UpdatePlayerInfo;
    var
      PlayerInfo: string;
    begin
      PlayerInfo := Format('%d %s %d %d', [turn, input, die[turn], wou[turn]]);
    
      // PlayerInfo now contains '1 Whatever 0 3'
    
      ListBox1.Items.Add(PlayerInfo);  // Display in a listbox
      Self.Caption := PlayerInfo;      // Show it in form's title bar
      ShowMessage(PlayerInfo);         // Display in a pop-up window
    end;
    

    当然,您总是可以直接转到ListBox,而不需要中间字符串变量:

      ListBox1.Items.Add(Format('%d %s %d %d', [turn, input, die[turn], wou[turn]]));
    

    Format 调用第一部分中的%d 和%s 是格式字符串,其中%d 表示整数的占位符,%s 表示整数的占位符细绳。该文档讨论了格式字符串here。

    【讨论】:

      【解决方案2】:

      另一种可能性是字符串连接(添加多个字符串以形成单个新字符串):

      // Given these values for turn, input, die[turn], and wou[turn]
      turn := 1;
      input := 'Whatever';
      die[turn] := 0;
      wou[turn] := 3;
      
      ListBox1.Items.Add(IntToStr(turn)+' '+input+' '+IntToStr(die[turn])+' '+IntToStr(wou[turn]));
      

      即。将各种元素加在一起:

      IntToStr(turn) // The Integer variable "turn" converted to a string
      +' ' // followed by a single space
      +input // followed by the content of the string variable "input"
      +' ' // followed by a single space
      +IntToStr(die[turn]) // element no. "turn" of the integer array "die" converted to a string
      +' ' // followed by a single space
      +IntToStr(wou[turn]) // element no. "turn" of the integer array "wou" converted to a string
      

      形成一个连续的字符串值,并将该值传递给 ListBox 的 Items 属性的“Add”方法。

      【讨论】:

      • 我不喜欢这样,因为它a) 更难阅读和维护,b) 需要对IntToStr 进行三个单独的调用,然后在每个返回值周围放置空格字符。这也使得本地化变得不可能。 Format 函数可以只传递一个resourcestring,它可以修改,因此可以很容易地更改。 (不是投反对票,而是解释为什么我不推荐这种方法。)
      • 这样做的好处是它是静态类型安全的。在实践中没什么大不了的。
      • @KenWhite:“更难阅读和维护”是一个主观术语。我发现它更容易阅读,因为当我从左到右阅读表达式时,我可以看到哪些值被放置在了哪里。 “格式”方法意味着我必须在格式字符串和参数列表之间来回扫描,以查看哪些值放在字符串中的哪个位置... YMMV ...
      • 谢谢,HeartWare。在我在这里发布问题之前,我尝试了这种方法,但不知何故,它总是会导致某种我无法理解的转换错误。还是不知道为什么:)
      猜你喜欢
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多