Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi XE3 - Can't concatenate strings

For the life of me, I cannot concatenate two(/three) strings. These are some codes I have tried:

dir := 'C:\Users\' + Username + '\Downloads\done.txt'; //"Username" is the computer's current username.
//another example vvv
dir := 'C:\Users\' + Username;
dir := dir + '\Downloads\done.txt';
//last example vvv
dir := Concat('C:\Users\', Username, '\Downloads\done.txt');

All of the examples always return the same result:

C:\Users\-username-

Never:

C:\Users\-username-\Downloads\done.txt

What am I doing wrong here?

like image 307
user1580845 Avatar asked Jan 21 '13 18:01

user1580845


People also ask

How do I concatenate strings in Delphi?

The Concat function concatenates all the strings given as arguments into a single string. It is the same as using the ` + ' operator: S1 + S2 + ... . The Concat function is built into the compiler and is not a real function. There is no performance difference between using the + operator and calling Concat .

How do you concatenate 2 strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

Can you use += for string concatenation?

The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .

How do I concatenate a string to a variable?

A common alternative is to use the addition (+) operator. Use the addition (+) operator to concatenate a string with a variable, e.g. 'hello' + myVar . The addition (+) operator is used to concatenate strings or sum numbers.


1 Answers

My guess is that your Username variable contains #0 at its end and you're outputing that variable to a certain Windows API function. For instance the following code will result to this misbehavior:

procedure TForm1.Button1Click(Sender: TObject);
var
  Dir: string;
  Username: string;
begin
  Username := 'Username' + #0;
  Dir := Concat('C:\Users\', Username, '\Downloads\done.txt');
  ShowMessage(Dir);
end;

My suggestion is to check the value of your Username variable and remove the extra #0 at the end if there's some.

like image 137
TLama Avatar answered Sep 22 '22 17:09

TLama