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?
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 .
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With