Concatenation

From Free net encyclopedia

In formal language theory (and therefore in programming languages), concatenation is the operation of joining two character strings end to end. For example, the strings "foo" and "bar" may be concatenated to give "foobar". In programming languages, string concatenation is usually accomplished by putting a concatenation operator between two strings (operands). The following statement assumes the language uses the "+" symbol as its concatenation operator:

print "Hello " + "World";

This code will print to the screen:

Hello World

Contents

Different languages

Different languages use different operators. Most languages use the "+" sign though several deviate from this norm:

  • BASIC, Pascal, Javascript, Java, Python, [[C++]] and Ruby use "+".
  • Perl (before version 6), PHP, and Maple (up to version 5) use the "." sign.
  • Perl 6 uses the "~" sign.
  • Visual Basic uses the "&" sign. It can also use the "+" sign but this leads to ambiguity if a string representing a number and a number is added together.
  • Standard SQL, PL/I, and Maple from version 6 uses double pipe signs ("||").
  • Mathematica uses "<>".
  • MATLAB uses the syntax "[x y]" to concatenate x and y.
  • Lua uses "..".
  • The J programming language uses ",".
  • Octave uses the syntax "[x, y]" to concatenate x and y.
  • Awk uses the empty string: you just have to write two expressions adjacent to each other to concatenate them. Unix shells have a similar syntax.
  • OCaml uses "^".

Some languages require the user call a function to concatenate a string of characters.

Interpolation

Some languages, notably Perl and PHP, can use a technique called interpolation that makes string concatenation easier. For example, in Perl, instead of typing:

my $stringVar;
$stringVar = "World";
print "Hello " . $stringVar;

one could type:

my $stringVar;
$stringVar = "World";
print "Hello $stringVar";

$stringVar gets interpolated in the rest of the string. The Perl interpreter prints Hello World instead of Hello $stringVar because a) the double quotes around the string indicate to the interpreter that it should be parsed for variables and character escapes, and b) it recognizes that $stringVar is a variable. It can do this because all scalar variables in Perl (and all variables in PHP) must begin with the "$" token whereas most languages don't usually require variables to have special characters.

Other uses of concatenation

In a Unix shell, the cat command can be used to concatenate files. The output of this concatenation can be a new file which consists of the content of two or more other files. However, the cat command is normally used merely to print a single file to the screen.

Concatenation in mathematics

In mathematics, concatenation is the joining of two strings, that is, when a and b are concatenated, they form ab. Concatenation of two strings, a and b is denoted as ab or a||b.

See also

de:Konkatenation (Listen) zh:串接