Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

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 2 days ago by avibootz
...