capri, a script language

Home | Documentation | Releases | Sources | Contact

Strings

Strings are a type of value. They are declared using either quotes " or primes '.

stringA = "I am a valid string.";
stringB = 'I am also a valid string.';
stringC = "It is possible to use 'primes' in a string with quotes.";
stringD = 'And t is possible to use 'quotes' in a string with primes.';

String concatenation & replacements

There are three ways to insert variables into a string, for example to create a command.

Concatenation: use the + operator to concatenate a string with any type of variable.

number = 25.32;
string = "The value is " + number;

Expressions in strings: anything within curly brackets {} (escapable with backslashes) is interpreted as an expression at the time the string is used immediately. With this feature you can write the above example cleaner:

number = 25.32;
string = "The value is {number}";

This feature allows you to write any type of expression within the curly brackets. The resulting value will be inserted there:

greeting = "Hello";
function getName() {
  return "Peter";
}
string = "{greeting} {getName()}!";

Shifting objects into strings: if you want to specify a command pattern and replace variables inside the string multiple times, you can use the << operator. A pattern is a string that has variables declared within dollar signs $ (escapable with backslashes). The left-hand-side of this operation must be a string, while the right-hand-side must be an object of which the keys are used as the variables to replace.

command_pattern = "program $file$";

foreach(file : File.listTree("test")) {
  command = command_pattern << {file: file};
  IO.println(command); 
}