2

How would I split a string to include the separators?

Lets say I had a string such as...

let myString = "apple banana orange grapes"

If I used

let separatedString = myString.componentsSeparatedByString(" ")

my resulting array would be

["apple","banana","orange","grapes"]

How would I achieve a result of

["apple ","banana ","orange ","grapes"]
3
  • Why do you want to do this? Do you have a specific reason for the extra space. If you really need it, you could also add the space later when your array is used. Commented Jul 14, 2016 at 17:59
  • @Asdrubal I'd like to keep the spaces because I'd like to keep track of the character count / location of each word from the original string. I also just wanted to avoid using NSRanges Commented Jul 14, 2016 at 18:10
  • Would something like this be of interest to you? github.com/mattgemmell/MGWordCounter Commented Jul 14, 2016 at 18:24

3 Answers 3

2

array.map lets you process the resulting array an add the space back in.

let separatedString = myString
  .componentsSeparatedByString(" ")
  .map { "\($0) " }

That last line iterates over all strings in the split up array and puts them in $0, and returns a new string with the space added back in which gets used as the replacement for the original string.

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

2 Comments

Would there be a way to adjust this answer for if there were multiple component separators? If the accepted separators were " " and "\n", how would you know which to insert?
Yeah that gets trickier. You'd need multiple passes, or regular expressions.
1

Alternative using regular expression:

let myString = "apple banana orange grapes"
let pattern = "\\w+\\s?"
let regex  = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matchesInString(myString, options:[], range: NSMakeRange(0, myString.characters.count))
  .map { (myString as NSString).substringWithRange($0.range)}
print(matches) // -> ["apple ", "banana ", "orange ", "grapes"]

2 Comments

from another comment in this thread, Would there be a way to adjust this answer for if there were multiple component separators? If the accepted separators were " " and "\n", how would you know which to insert?
@bremmm This regex considers space characters as well as \t, \n, \r. The pattern does: Catch any alphanumeric character (one or more) followed by an (optional) whitespace character. There is no insertion, the respective whitespace character after the match is included.
1

Solution

Since you updated your question, it looks now you no longer want a new space on the last word.

So here's my updated code

let text = "apple banana orange grapes"

let chunks: [String] = text
    .componentsSeparatedByString(" ")
    .reverse()
    .enumerate()
    .map { $0.element + ( $0.index == 0 ? "" : " ") }
    .reverse()

print(chunks) // ["apple ", "banana ", "orange ", "grapes"]

Multiple separators

Thank to @vadian for the suggestion

let text = "apple banana\norange grapes"

let chunks: [String] = text
    .componentsSeparatedByCharactersInSet(.whitespaceAndNewlineCharacterSet())
    .reverse()
    .enumerate()
    .map { $0.element + ( $0.index == 0 ? "" : " ") }
    .reverse()

print(chunks) // ["apple ", "banana ", "orange ", "grapes"]

4 Comments

from another comment of mine in this thread, Would there be a way to adjust this answer for if there were multiple component separators? If the accepted separators were " " and "\n", how would you know which to insert?
@bremmm: Please see the Multiple separators section in my answer
@appzYourLife componentsSeparatedByCharactersFromSet with whitespaceAndNewlineCharacterSet for multiple separators might be more appropriate.
@vadian: You are totally right. Thank your for the hint!

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.