A.I, Data and Software Engineering

String interpolation in different programming languages

S

String is important data type in every programming language. They are used to display text and involved in various language processing applications. So, this article quickly lists out several examples to create and manipulate a string from data in different programming languages.

A string example - A styled string - string interpolation
A string example – A styled string

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literalcontaining one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simple template processing or, in formal terms, a form of quasi-quotation (or logic substitution interpretation). String interpolation allows easier and more intuitive string formatting and content-specification compared with string concatenation.

String in C

char s1[20];             // Character array - can hold a C string, but is not yet a valid C string
char s2[20] = { 'h', 'e', 'l', 'l', 'o', '
char s1[20];             // Character array - can hold a C string, but is not yet a valid C string
char s2[20] = { 'h', 'e', 'l', 'l', 'o', '\0' };     // Array initialization
char s3[20] = "hello";      // Shortcut array initialization
char s4[20] = "";        // Empty or null C string of length 0, equal to ""
' }; // Array initialization char s3[20] = "hello"; // Shortcut array initialization char s4[20] = ""; // Empty or null C string of length 0, equal to ""

Store concatenated string in a buffer

char buffer[1024];
snprintf(buffer, sizeof(buffer), "Dealer's Card is %C %C", char1, char2);

String in C++

In C++, the same syntax of C can be applied. But there are a more C++ way by using string class.

#include <iostream>
#include <string>
using namespace std;
int main () {
   //Declare three variables str1, str2, str3
   string str1 = "Hello";
   string str2 = "World";
   string str3;
   int  len ;
   // copy str1 into str3
   str3 = str1;
   // concatenates str1 and str2
   str3 = str1 + str2;
   return 0;
}

You can use string format for a string interpolation:

string s = str( format("%2% %2% %1%\n") % "world" % "hello" );
// s contains "hello hello world"

String in C#

//Declare a string variable name
string name = "Tom";
var date = DateTime.Now;
// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// Output: Hello, Tom! Today is Wednesday, it's 19:40 now.

In C#, you can use the following syntax with </strong>: <!-- /wp:paragraph --> <!-- wp:quote --> <blockquote class="wp-block-quote">{<interpolatedExpression>[,<<a href="https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting#alignment-component">alignment</a>>][:<<a href="https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting#format-string-component">formatString</a>>]}</blockquote> <!-- /wp:quote --> <!-- wp:paragraph --> Note that: You cannot have any white space between the <code> and the " that starts a string literal.

const int FieldWidthRightAligned = 20;
Console.WriteLine("{Math.PI,FieldWidthRightAligned:F3}"); //Math.PI = The String to be formatted (expression) //FieldWidthRightAligned = 20 (alignment) //F3 = format 3 decimal of a float (formatString) </pre> <!-- /wp:preformatted --> <!-- wp:paragraph --> And another example of string with field data inserted: <!-- /wp:paragraph --> <!-- wp:preformatted --> <pre class="wp-block-preformatted">Console.WriteLine("Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Output: Hello, Tom! Today is Wednesday, it's 19:40 now.

String in Java

Java creates String object by concatenation.

String name = "Tom";
String s = 1 + "Hello " + name;
//Output: 1Hello Tom

We can also use string format() to create a string object:

int x = 5, y = 4;
System.out.println(String.format("%d * %d = %d", x, y, x * y));
//output: 5 * 4 = 20

String in Python

Python 3.6 added new string interpolation method called literal string interpolation and introduced a new literal prefix f.

name = 'World'
program = 'Python'
print(f'Hello {name}! This is {program}')
#output: 12 multiply 3 is 36.

%-formatting

name = 'world'
program ='python'
print('Hello %s! This is %s.'%(name,program))
#Hello world! This is python.

We can use format() function on a string object and braces {}, the string object in format() function is substituted in place of braces {}.

name = 'world'
print('Hello, {}'.format(name))
#output: Hello,world

String in Dart

You can access the value of an expression inside a string by using {expression}</code>. <!-- /wp:paragraph --> <!-- wp:code --> <pre class="wp-block-code"><code>var greeting = "Hello"; var person = "Tom"; print("{greeting}, {person}!"); // prints "Hello, Tom!" </code></pre> <!-- /wp:code --> <!-- wp:paragraph --> If the expression is an identifier, the <code>{}</code> can be skipped. <!-- /wp:paragraph --> <!-- wp:code --> <pre class="wp-block-code"><code>print("greeting, person"); </code></pre> <!-- /wp:code --> <!-- wp:paragraph --> If the variable inside the <code>{}</code> isn't a string, the variable's <code>toString()</code> method is called: <!-- /wp:paragraph --> <!-- wp:code --> <pre class="wp-block-code"><code>int x = 5; print("There are{x.toString()} people in this room");

String in Kotlin

val age : Int = 24
var mySuperString : String = "Dato is {age} years old!" println(mySuperString)</pre> <!-- /wp:preformatted --> <!-- wp:heading {"level":3} --> <h3>String in SWIFT</h3> <!-- /wp:heading --> <!-- wp:paragraph --> We can insert variables in a String usinglatexvar).

let name = "Tom"
let greeting = "Hi there, \(name)"
#output: "Hi there, Tom"

You can also use extended string delimiters (SWIFT 5.X+) to create strings containing characters that would otherwise be treated as a string interpolation (surround the string with number signs (#) ). For example:

let someval = 3
print(#"Write an interpolated string in Swift using \(someval)."#)
// Prints "Write an interpolated string in Swift using \(multiplier)."
print(#"6 times 7 is \#(6 * 7)."#)
// Prints "6 times 7 is 42."

3 comments

💬

  • There section about interpolation in Swift is broken, it should be like this:
    `let greeting = “Hi there, \(name)”`

    • Thanks heaps. I have updated the content! The error was due to the batch processing using search and replacement from the database.

  • There section about interpolation in Swift is broken, it should be like this:
    `let greeting = “Hi there, \(name)”`

A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.