Open In App

String Functions and Operators in Swift

Last Updated : 03 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A string is a sequence of characters that is either composed of a literal constant or the same kind of variable. For eg., “Hello World” is a string of characters. In Swift4, a string is Unicode correct and locale insensitive. We are allowed to perform various operations on the string like comparison, concatenation, iteration, and many more. 

Swift-String

 

We can create a string either by using a string instance or creating an instance of a string class. The following are the commonly used methods to create a string in Swift:

By using String Instance

To create a string we can use a String() initializer. It will create an instance of a string. 

Syntax:

var str = String(“Hello GFG)

Example:

Swift




// Swift program to illustrate how to create a string
 
// Here String() is used for string instance
var s = String("Hello Everyone!!!"
 
print(s)


Output:

Hello Everyone!!!

By using String Literal

Here, we use double apostrophes on the words for the formation of strings, similar as, normal strings in other languages. Or we can use a String data type to create a string type variable.

Syntax:

var str = ” Welcome”

var s:String = “Hello”

Example:

Swift




// Swift program to illustrate how to create a string
 
// Create strings
var str1 = "Hello Everyone"
print(str1)
 
var str2: String = "Welcome Everyone"
print(str2)


Output:

Hello Everyone
Welcome Everyone    

Multi-line Strings

Apart from single-line strings, we can also create multi-line strings. For the creation of multi-line strings, instead of double quotes, we have to use triple quotes at the end and start of the string(“””). 

Syntax:

var str = “”” 

                Hello world

                How are you ?

               “””

Example:

Swift




// Swift program to illustrate how to create multi-line string
 
// Creating multi-line string
let str = """
           Hello People!!!
           This is an example
           of multiline string
           """
print(str)


Output:

Hello People!!!
This is an example
of multiline string

String Functions and Operators

Now, we will see some commonly used functions and operators related to a string: 

Empty String

Empty string is a type of string whose length is equal to zero. Or in other words, it’s a sequence of zero characters in a string. For creating an empty string, either we can create a string literal with single quotes only or by passing an argument with no values in it. Sometimes people get confused between an empty string and a null string. Null string means which has no value at all in it. In other words, it can also be defined as the absence of a string instance. 

Example:

Swift




// Swift program to create empty string
 
// With empty string literal
var Q = ""
 
// With no values passed in an argument
var E = String() 


isEmpty

Swift provides an inbuilt property to check whether the given string is empty or not. It will return true if the given string is empty. Otherwise, it will return false. 

Syntax:

str.isEmpty

Example:

Swift




// Swift program to illustrate isEmpty property
 
// Creating a string
var str1 = ""
 
// Checking if the given string is empty or not
if str1.isEmpty
{   
   print("str1 is empty")
} else {
   print("str1 is not empty"
}
 
// Creating another string
let str2 = "hello Jeevan"
 
// Checking if the given string is empty or not
if str2.isEmpty
{
   print("str2 is empty")   
} else {
   print("str2 is not empty")
}


Output:

str1 is empty
str2 is not empty

String Length

The length of a string can be defined as the total number of characters present in the string. The Count property is used for counting the length of the string. The length of an Empty string is zero. 

 Syntax:

str.count

Example:

Swift




// Swift program to illustrate count property
 
// Creating a string
var s = "Hello Sudha! How are you?"
 
// Count property is used to count the length of the string.
var len = s.count
print("Length of str is \(len)")


Output:

Length of str is 25

String Concatenation

Concatenation is the addition of one or more strings to the end of another string. For string literals and string constants, concatenation occurs at compile time. For string variables, concatenation occurs only at run time. For the concatenation of strings, we have to use the ‘+’ operator to concatenate either strings or strings, or strings and characters, or characters and characters. 

Syntax:

  var s = string1 + string2

Example:

Swift




// Swift program to illustrate string concatenation
 
// Creating strings
var str1 = "Hello"
var str2 = " People!"
var str3 = "My"
var str4 = "Name"
var str5 = "is"
var str6 = "Max."
 
// Concatenating two strings using + operator
var s1 = str1 + str2
print(s1)
 
// Concatenating multiple strings using + operator
var s2 = str3 + " " + str4 + " " + str5 + " " + str6
print(s2)


Output:

Hello People!
My Name is Max.

String Comparison

To check whether the given strings are the same or not we use equal to(==), and not Equal to(!=) operators. Both operators are the most commonly used operator to compare two strings. Here both the operators return true if the given strings fulfill the condition. Otherwise, return false. 

Syntax:

string1 == string2

or

string1 != string 2

Example:

Swift




// Swift program to illustrate string comparison
 
// Creating strings
var str1 = "hello"
var str2 = "hello" 
var str3 = "Krishna"
 
// Comparing the equality of two strings
if (str1 == str2)
{
    print("\(str1) is equal to \(str2)")
}
else
{
    print("\(str1) is not equal to \(str2)")
 
// Comparing the not equality of two strings
if (str1 != str3)
{
    print("\(str1) is not equal to \(str3)")
}
else
{
    print("\(str1) is equal to \(str3)")
}


Output:

hello is equal to hello
hello is not equal to Krishna

Greater than Operator

To check if the given string is greater than another string we use the greater than operator(>). Here, > operator returns true if the first string is greater than another string. Otherwise, it will return false. 

Syntax:

string1>string2  

Example:

Swift




// Swift program to check if the given string
// is greater than another string or not
 
// Creating strings
var str1 = "hen"
var str2 = "cow"
 
// Finding largest string
if (str1 > str2)
{
    print("\(str1) is greater than \(str2)")
}
else
{
    print("\(str1) is not greater than \(str2)")
}


Output:

hen is greater than cow

Less than Operator

To check if the given string is less than another string we use the less than operator(<). Here, < operator returns true if the first string is less than another string. Otherwise, it will return false. 

Syntax:

string1<string2 

Example:

Swift




// Swift program to check if the given string
// is less than another string or not
 
// Creating strings
var str1 = "Ant"
var str2 = "cow"
 
// Finding largest string
if (str1 < str2)
{
    print("\(str1) is less than \(str2)")
}
else
{
    print("\(str1) is not less than \(str2)")


Output:

Ant is less than cow

hasPrefix(prefix: String)

This function is used to check whether a given parameter string exists as a prefix of the string or not. If the string exists as a prefix in the other string, then it will return true. Otherwise, return false.

Syntax:

string1.hasPrefix(string2)

Example:

Swift




// Swift program to illustrate hasPrefix() function
 
// Creating strings
var string1 = "hello Suman"
var string2 = "hell" 
 
// Checking whether a given parameter string exists
// as a prefix of the string or not
var result = string1.hasPrefix(string2)
 
print("Does string1 starts with string2? \(result)")


Syntax:

Does string1 starts with string2? true

hasSuffix(suffix: String)

This function is used to check whether a given parameter string exists as a suffix or not.  If the string exists as a suffix in the other string, then it will return true. Otherwise, return false.

Syntax:

string1.hasSuffix(str2)              

Example:

Swift




// Swift program to illustrate hasSuffix() function
 
// Creating strings
var string1 = "hello Suman"
var string2 = "man"
 
// Checking whether a given parameter string exists
// as a suffix of the string or not
var result = string1.hasSuffix(string2)
 
print("Does string1 ends with string2 : \(result)")


Output:

Does string1 ends with string2 : true

String.lowercased()

Lowercase means small letter alphabets. Here, we use this function for the conversion of all characters into lowercase characters in the given string. 

Syntax:

string.lowercased()  

 Example:

Swift




// Swift program to illustrate lowercased() function
 
// Creating strings
var string = "Hello People"
 
// Conversion of every characters of the string into lowercase
var result = string.lowercased()
 
print("Original String: \(string)")
print("Lowercase String: \(result)")


Output:

Original String: HellO PeoPle
Lowercase String: hello people

String.uppercased()

Uppercase means capital letter alphabets. Here, we use this function for the conversion of all characters into uppercase characters in the given string.

Syntax: 

String.uppercased()         

Example: 

Swift




// Swift program to illustrate uppercased() function
 
// Creating strings
var string = "HellO PeOpLe"
 
// Conversion of every characters of the
// string into uppercase
var result = string.uppercased()
 
print("Original  String : \(string)")
print("Uppercase String : \(result)")


Output:

Original  String : HellO PeOpLe
Uppercase String : HELLO PEOPLE

String.reversed()

Reversing a string means changing the order of a given string so that the last character of the string becomes the first character of the string and so on. This function is used for doing the reverse of the given string. With the help of this function, we can also check whether the string is ‘Palindrome’ or not. Palindrome means the sequence of characters which reads the same from backward as well as forwards, like, noon.

Syntax: 

String. reversed() 

Example:

Swift




// Swift program to illustrate reversed() function
 
// Creating string
var string = "Hello People"
 
// Reversing the string
var result = String(string.reversed())
 
// Print the output
print("Original String : \(string)")
print("Reversed String : \(result)")


Output:

Original String : Hello People
Reversed String : elpoeP olleH

String.insert()

This function is used for inserting a character at a specified index in the string. 

Syntax:

string1.insert(ch, at: I)          

where ‘ch’ defines the character which has to be inserted and ‘i’ defines the index of the string at which ‘ch’ is to be inserted

Example:

Swift




// Swift program to illustrate insert() function
 
// Creating string
var string1 = "Hello People!"
var ch :Character = "x"
 
var i = string1.index(string1.startIndex, offsetBy: 5)
 
// Here, character 'x' is inserted at the position 'i'
// which is here 5 in the string.
string1.insert(ch, at: i)
 
// Printing the output
print(string1)


Output:

Hellox People!

String.remove(at:)

This function is used for removing characters at a specified index in the string. 

Syntax: 

string1.remove(at: I)                         

where ‘i’ is the index in the string from which the character will get removed.

Example:

Swift




// Swift program to illustrate remove() function
 
// Creating string
var str1 = "Hello People!"
 
print("Original string: \(str1)")
 
// String's index which has to be removed
var i = str1.index(str1.startIndex, offsetBy: 6)
 
// Function 'remove' is used
var removed = str1.remove(at: i)
 
print("String after remove() : \(str1)")
print("Character Removed : \(removed)")


Output:

Original string: Hello People!
String after remove() : Hello eople!
Character Removed : P


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads