Many times we need to embed values from variables or constants in a string to display that string on screen. It is not necessary to to use concatenate function each time. There are shortcuts in many programming languages to achieve this embeding.
Swift
In swift, you have to enclose the variable or constant inside brackets () and escape it with a backslash character.
1 2 3 4 5 |
var role:String = “Developer” var name:String = “Jitendra” // embed and print values of variables print(“Hi! My name is \(name). I am a \(role).”) |
Result will be :
Hi! My name is Jitendra. I am a Developer.
Kotlin
in Kotline, you have to append variable name with dollar Sign $ inside string template.
1 2 3 4 5 |
var name:String = “Jitendra” var role:String = “Developer” // embed and print values of variables print(“Hi! My name is $name. I am a $role.”) |
Result will be :
Hi! My name is Jitendra. I am a Developer.
JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
String firstString = “Democracy” String secondString = “People” //Using + method String quote = firstString + ” is a government of the “ + secondString; //Using format() method String.format( “%s is a government of the %s”, firstString, secondString); //Using MessageFormat.format() method MessageFormat.format(“{0} is a government of the {1}”, firstString, secondString); |
Result will be :
Democracy is a government of the People.
JAVAScript
In javascript, ${ } format is used. Anything can be placed inside brackets including functions, calculations, variables, constants.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<script> // DEclare and initialize variables const x = “Jitendra”; // I like Jitendra console.log(`I like ${x}.`); // Function call function greet() { return “hello!”; } // hello! I am a developer. console.log(`${greet()} I am a developer.`); // Expression evolution //sum of 4 and 6 is 10. console.log(`sum of 4 and 6 is ${4+6}.`); </script> |
PHP
In PHP, variables can be embedded by appending dollar sign to variable. {} curly brackets can also be used as extra for easy differentiation with other text.
1 2 3 4 5 6 7 8 9 10 |
$name = ‘Rakesh’; // $name will be replaced with `Rakesh` echo “<p>Hello $name, Happy Birthday.</p>”; echo “<p>Hello {$name}, Happy Birthday.</p>”; # ↕ #> “<p>Hello Rakesh, Happy Birthday.</p>” |