Delphi 如何将多个值组合成一个字符串?

Delphi 如何将多个值组合成一个字符串?,delphi,listbox,Delphi,Listbox,我正在努力学习德尔菲,目前正在制作一个游戏。我以前懂一点帕斯卡语,但我对德尔福一无所知。几年前我用帕斯卡做了这个游戏。它包含这样一行: writeln(turn,' ',input,' ',die[turn],' ',wou[turn]); 基本上,它是为了显示用户输入的计算结果,这些数字之间有一些空格。所有这些变量都是数字,但输入除外,输入是字符串 我试图在Delphi中以类似的方式显示结果。虽然最好使用一张桌子,但我不知道如何使用,所以我尝试使用一个列表框。但是items.add过

我正在努力学习德尔菲,目前正在制作一个游戏。我以前懂一点帕斯卡语,但我对德尔福一无所知。几年前我用帕斯卡做了这个游戏。它包含这样一行:

writeln(turn,'  ',input,'   ',die[turn],'  ',wou[turn]);
基本上,它是为了显示用户输入的计算结果,这些数字之间有一些空格。所有这些变量都是数字,但输入除外,输入是字符串

我试图在Delphi中以类似的方式显示结果。虽然最好使用一张桌子,但我不知道如何使用,所以我尝试使用一个列表框。但是items.add过程不像Pascal的writeln那样工作,因此我现在被卡住了

我是初次学习的新手,所以请让我容易理解。

使用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]]));

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

另一种可能性是字符串串联,将多个字符串相加以形成一个新字符串:

// 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:更难阅读和维护是一个主观术语。我发现它更容易阅读,因为当我从左到右阅读表达式时,我可以看到哪些值被放置在哪里。Format方法意味着我必须在Format字符串和参数列表之间来回扫描,以查看哪些值放置在字符串中的位置。。。YMMV…谢谢,HeartWare。在我把问题贴在这里之前,我尝试过这种方法,但不知怎么的,它总是导致某种转换错误,我无法理解。还是不知道为什么: