How to convert a string to an array of characters in Swift

1 Answer

0 votes
import Foundation

/*
 A Swift String is a collection of Character values.

 In many cases, you can iterate directly over a String without
 converting it. However, some algorithms require random access
 to individual characters or an explicit array representation.

 This example demonstrates how to convert a String into an
 Array<Character> using a dedicated function.
 */

/*
 Converts a String into an array of Character values.

 Parameter text:
   The source string.

 Returns:
   An array containing each character from the input string.

 Notes:
   - Swift strings are Unicode-aware.
   - A Character may represent more than one Unicode scalar.
   - Using Array(text) preserves Swift's correct handling of
     extended grapheme clusters (such as emoji and accented
     characters).
 */
func stringToCharacterArray(_ text: String) -> [Character] {
    return Array(text)
}

func main() {
    let text = "Hello, World!"

    // Convert the string into an array of characters.
    let characters = stringToCharacterArray(text)

    print("Original string: \(text)")
    print()
    print("Character array contents:")

    for (index, character) in characters.enumerated() {
        print("characters[\(index)] = '\(character)'")
    }
}

main()


/*
run:

Original string: Hello, World!

Character array contents:
characters[0] = 'H'
characters[1] = 'e'
characters[2] = 'l'
characters[3] = 'l'
characters[4] = 'o'
characters[5] = ','
characters[6] = ' '
characters[7] = 'W'
characters[8] = 'o'
characters[9] = 'r'
characters[10] = 'l'
characters[11] = 'd'
characters[12] = '!'

*/

 



answered Oct 3 by avibootz
...