Swift Program to convert the string into an array of characters


To convert the string into an array of characters Swift proved the following methods −

  • Using Array() initialiser

  • Using append() method

Input

String = “Cloudy day”

Output

Array = [“C”, “l”, “o”, “u”, “d”, “y”, “d”, “a”, “y”]

Here we converted all the characters present in the input string into the array of characters.

Method 1: Using Array() initialiser

Swift supports an Array() initialiser which is used to convert the input string into an array of characters. Or we can say that Array() initialiser is used to create array objects. Here we use parametrised array.

Syntax

Array(value)

Here value represents the string which we want to convert into an array of characters.

Example

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

import Foundation
import Glibc

let sentence = "Learn Swift"

print("Original String:", sentence)
let charArray = Array(sentence)

print("Array of character:", charArray)

Output

Original String: Learn Swift
Array of character: ["L", "e", "a", "r", "n", " ", "S", "w", "i", "f", "t"]

Method 2: Using the append() method

We can also use the append() method to add each character of the given string into the array of characters. The append() method add an element or character at the end of the array.

Syntax

func append(value)

Here value represents the element which we want to append at the end of the array.

Example

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

import Foundation
import Glibc

let sentence = "Learn Swift"

var charArray = [Character]()

// Iterate through each character in the given string 
// and then append into the array
for C in sentence{
   charArray.append(C)
}

print("Array of characters: ", charArray)

Output

Array of characters:  ["L", "e", "a", "r", "n", " ", "S", "w", "i", "f", "t"]

Conclusion

So this is how we can convert the string into an array of characters using the Array() and append() methods. Both methods work efficiently. The append() method provides you more freedom because here you can access each character one by one whereas Array() function does not because it converts the string into an array directly without iterating through characters.

Updated on: 10-May-2023

978 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements