How to Print a String in Swift Program?


This tutorial will discuss how to write a swift program toprint a string. A string is a collection of characters such as “TutorialsPoint”, “Hello Purnima! How are you?”, etc. Strings can also be represented by Unicode. We can easily create and modifies a strings because they are lightweight and readable, also we can do string interpolation. Strings can be used to insert variable, constants expressions, etc.

Syntax

Following is the syntax for creating string type variable

Var a : String

Algorithm to print two strings

  • Step 1 − Define 2 Variables

  • Step 2 − Enter string into that variable

  • Step 3 − Perform operations with that string

  • Step 4 − Print the output

Example

Print a String

The following program shows how to print a string.

import Foundation
import Glibc

var string1 : String
var string2 : String

string1 = "Welcome to tutorialspoint"
string2 = "How are you tutorialspoint?"
print("String 1: ", string1)
print("String 2: ", string2)

Output

String 1: Welcome to tutorialspoint
String 2: How are you tutorialspoint?

Example

Print a multiline String

The following program shows how to print a multiline string. Here multilines are enclosed in three double quotes.

import Foundation
import Glibc

var MultilineData = """
Hello Friends I m Sona. I like to travel very much.
I also love to cook food
"""

print(MultilineData);

Output

Hello Friends I m Sona. I like to travel very much.
I also love to cook food

Example

Print a string

The following program shows how to print a string. Here, we do string interpolation

import Foundation
import Glibc

var Tname = "Sumu"
var Pname = "Momos"

print("Hello! \(Tname) likes \(Pname) vary much.")

Output

Hello! Sumu likes Momos vary much.

String interpolation means a new string is created by mixing the constant(e.g.,max), expression, variables(e.g., value), and literals along with their values inside the string literal. To insert the values of constant, variable, expression, and literals in string, we use a backslash(\) followed by the values enclosed in the parentheses.

Updated on: 29-Jul-2022

528 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements