Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift string separation but include the

Tags:

string

swift

I need to separate a string to a array of substring but need to include ",.?!" as the substring in Swift.

var sentence = "What is your name?" into
var words = ["What", "is", "your", "name", "?"]

I know I can use this to separate the white space, but I need the ".,?!" to be separated into a word in the words array. How can I do that?

var words = sentence.components(separatedBy: " ")

I only get ["What", "is", "your", "name?"]

I need to separate the ? at the end word, and make words array like this:

var words = ["What", "is", "your", "name", "?"]
like image 546
Emmy Avatar asked Apr 18 '20 22:04

Emmy


1 Answers

You can enumerate your substrings in range using .byWords options, append the substring to your words array, get the substring range upperBound and the enclosed range upperBound, remove the white spaces on the resulting substring and append it to the words array:


import Foundation

let sentence = "What is your name?"
var words: [String] = []
sentence.enumerateSubstrings(in: sentence.startIndex..., options: .byWords) { substring, range, enclosedRange, _ in
    words.append(substring!)
    let start = range.upperBound
    let end = enclosedRange.upperBound
    words += sentence[start..<end]
        .split{$0.isWhitespace}
        .map(String.init)
}

print(words) // "["What", "is", "your", "name", "?"]\n"

You can also use a regular expression to replace the punctuation by the same punctuation preceded by a space before splitting your words by whitespaces:

let sentence = "What is your name?"
let words = sentence
    .replacingOccurrences(of: "[.,;:?!]",
                          with: " $0",
                          options: .regularExpression)
    .split{$0.isWhitespace}

print(words)  // "["What", "is", "your", "name", "?"]\n"

Swift native approach:

var sentence = "What is your name?"
for index in sentence
    .indices
    .filter({ sentence[$0].isPunctuation })
    .reversed() {
    sentence.insert(" ", at: index)
}
let words = sentence.split { $0.isWhitespace }
words.forEach { print($0) }

This will print:

What

is

your

name

?

like image 87
Leo Dabus Avatar answered Nov 15 '22 07:11

Leo Dabus