divide a text by words and then group those words by groups of three characters. in swift

main.swift
let inputString = "This is a sample text"
let components = inputString.components(separatedBy: .whitespaces)
var GroupsOfThreeChars = [String]()

for component in components {
    let characters = Array(component)
    for index in 0..<(characters.count/3 + 1) {
        let start = index * 3
        let end = min((index+1) * 3, characters.count)
        GroupsOfThreeChars.append(String(characters[start..<end]))
    }
}

print(GroupsOfThreeChars)
449 chars
15 lines

In this code, we first split the input string into an array of components using the components(separatedBy:) method with whitespace as the separator. Then, we create an empty array to store the groups of three characters.

We use a nested for loop to iterate over each component and each group of three characters within each component. For each component, we convert the string to an array of characters and iterate over the array in groups of three characters. We append each group of three characters to the GroupsOfThreeChars array.

Finally, we print the GroupsOfThreeChars array to the console.

gistlibby LogSnag