1

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.

2
  • 1
    You forgot to add the code you've written so far. Commented Apr 7, 2018 at 1:38
  • I try some but it didn't work. Commented Apr 7, 2018 at 1:42

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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"]

1 Comment

Thanks for your help but I'm looking for Regex solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.