30

What is the recommended way of concatenation of strings?

1

5 Answers 5

52

Tcl does concatenation of strings as a fundamental operation; there's not really even syntax for it because you just write the strings next to each other (or the variable substitutions that produce them).

set combined $a$b 

If you're doing concatenation of a variable's contents with a literal string, it can be helpful to put braces around the variable name or the whole thing in double quotes. Or both:

set combined "$a${b}c d" 

Finally, if you're adding a string onto the end of a variable, use the append command; it's faster because it uses an intelligent memory management pattern behind the scenes.

append combined $e $f $g # Which is the same as this: set combined "$combined$e$f$g" 
Sign up to request clarification or add additional context in comments.

2 Comments

Note that the first argument to append is a variable name, just like the first arg to set.
This isn't really right in that you can't write arbitrary strings back-to-back and get their concatenation. E.g. "a""b" , or {foo}"bar" don't work. It's more true in awk, where something like $1 ":" $2 does work.
32

Use append.

set result "The result is " append result "Earth 2, Mars 0" 

Comments

8

If they are contained in variables, you can simply write "$a$b".

2 Comments

I am doing exactly in the way you have written with a small difference like ${a}${b}, but I worry that it is not a correct way to do, is it?
They are both right - you would use the ${a}${b} construction in the case where you are building a string and there may be an ambiguity about the variable name e.g. set url /admin/item-edit?item_name=${item_id}name
3

These days, you can concatenate two literal strings using the "string cat" command:

set newstring [string cat "string1" "string2"] 

Comments

0
# using join set a {abcd} set b {efgh} set l [list $a $b] # a list set c [join $l ] # space sep (default) set d [join $l {}] # no sep puts $c abcd efgh puts $d abcdefgh 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.