Swift Program to convert the array of characters into the string


To convert the array of characters into a string Swift provides the following methods −

  • Using String() initialiser

  • Using append() method

Input

array = [“S”, “w”, “i”, “f”, “t”]

Output

Swift

Here we join all the characters given in the array to create a string.

Method 1: Using String() Initialiser

To convert the array of characters into a string we can use String() initialisers. The String() initialiser will create the object of a string. Here we use parameterise string initialiser.

Syntax

Swift(value)

Here value represents the array which we want to convert into a string.

Example

In the following Swift program, we will convert the array of characters into a string. So create an array of characters, then use String() initialiser to convert the given array of characters into a string and store the result into a string. Finally display the resultant string.

import Foundation
import Glibc

let CharArr: [Character] = ["S", "w", "i", "f", "t", "!"] 

let newStr = String(CharArr) 

print("String:", newStr)

Output

String: Swift!

Method 2: Using append() Method

We can also use the append() method to convert the array of characters into a string. Using the append() method we can add elements of the given array into a string.

Syntax

func append(element)

Here element represents the element which we want to append.

Example

In the following Swift program, we will convert the array of characters into a string. So for that, we will create an array of characters and an empty string. Then run a for-in loop to iterate through each character of the array and then append the current character to the string. Finally will display the resultant array.

import Foundation
import Glibc

let CharArr: [Character] = ["T", "u", "t", "o", "r", "i", "a", "l", "s", "p", "o", "i", "n", "t"]
var Str = String() 

// Iterate through each character in the array 
// and add it to the string
for c in CharArr {
   Str.append(c)
}

print("String:", Str)

Output

String: Tutorialspoint

Conclusion

So this is how we can convert the array of characters into a string using String() and append() methods. Both methods have their own benefits like using a String() initializer you do not require any extra loop to convert the array of characters into the string. Whereas using the append() function you need a for-in loop to iterate through each character of the array, then add them into the string. In the append() function, you have a choice as to which element you want to add in the string or not whereas in the String() initializer you don't have.

Updated on: 09-May-2023

443 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements