Trung Phan
Trung Phan

Reputation: 923

Swift regular expression split string into array of substring with length

How to split the input string into an array of string?

The substring will be less than or equal a constant length (ex:10 characters in total.)

The substring will only be split on white space.

Ex: The quick brown fox jumps over the lazy dog Should split into array of

["The quick","brown fox","jumps over","the lazy", "dog"] 

=> Each item in array less than or equal 10 chars and separated by white space.

Upvotes: 1

Views: 2016

Answers (2)

Rob
Rob

Reputation: 437432

You can use /(.{1,10})(\s+|$)/, matching between 1 and 10 characters, terminated with whitespace or end of line.

let string = "The quick brown fox jumps over the lazy dog"
let regex = /(.{1,10})(\s+|$)/
let results = string.matches(of: regex)
    .map { $0.1 }

Yielding:

["The quick", "brown fox", "jumps over", "the lazy", "dog"]

Like with all regex answers, there are many ways to skin the cat, but this seems to be one simple approach.

This does, though, beg the question of what to do if it encounters a word with more than 10 characters, though. If, for example, you wanted to permit those long words without splitting them, you might use "/(.{1,10}|\S{11,})(\s+|$)/".


By the way, this uses Regex. If you want to use the legacy NSRegularExpression, see the prior revision of this answer.

Upvotes: 4

Gi0R
Gi0R

Reputation: 1457

import Foundation

var foxOverDog = "The quick brown fox jumps over the lazy dog".components(separatedBy: " ")

var foxOverDogFitted = foxOverDog.reduce(into: [""]) {
    if $0[$0.endIndex - 1].count + $1.count <= 10 {
        let separator: String = $0[$0.endIndex - 1].count > 0 ? " " : ""
        $0[$0.endIndex - 1] += separator + $1
    } else {
        $0.append($1)
    }
}
print(foxOverDogFitted) // ["The quick", "brown fox", "jumps over", "the lazy", "dog"]

Upvotes: 0

Related Questions