user3055069
user3055069

Reputation: 11

How do I combine multiple values into a single string?

I'm trying to learn Delphi and I'm currently making a game. I used to know a bit Pascal, but I know nothing about Delphi. I made this game in Pascal a few years ago. It contains a line like this:

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

Basically it is meant to show up the calculated results for an user input, with a few spaces between those numbers (all those variables are numbers except "input", which is a string).

I'm trying to display the results similarly in Delphi. Though it would be best to use a table, I have no idea how to use one, so I tried with a listbox. But the items.add procedure does not work like Pascal's writeln, thus I'm currently stuck.

I'm a new, first-time learner, so please make things easy to understand for me.

Upvotes: 1

Views: 2933

Answers (2)

Ken White
Ken White

Reputation: 125688

Use the Format function, from the SysUtils unit. It returns a string that you can use anywhere you can use a string:

// 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;

You can always, of course, go directly to the ListBox without the intermediate string variable:

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

The %d and %s in first part of the Format call are format strings, where %d represents a placeholder for an integer and %s represents a placeholder for a string. The documentation talks about format strings here.

Upvotes: 7

HeartWare
HeartWare

Reputation: 8243

Another possibility is String Concatenation (adding of multiple strings to form a single new string):

// 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]));

ie. addding together the various elements:

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

to form a single continous string value, and passing that value to the "Add" method of the ListBox's Items property.

Upvotes: 1

Related Questions