Ryan
Ryan

Reputation: 119

Split a String in Swift While Keeping Split String

How could you split a string into an array while keeping the separating string?

You can split a string by doing this but it doesn't keep the separator substring:

"My-Name".components(separatedBy: "-") -> ["My", "Name"]

This is what I'm trying to achieve:

Ex 1: "My-Name".someSplitFunc(separatedBy: "-") -> ["My-", "Name"]

Ex 2: "This-is-a-sentence".someSplitFunc(separatedBy: "-") -> ["This-", "is-", "a-", "sentence"]

Upvotes: 1

Views: 232

Answers (2)

AMIT
AMIT

Reputation: 924

Simply use this extension below.

extension String {
    func componentSeparate(by: String) -> [String] {
        var out: [String] = [String]()
        var storeStr = ""
        for str in Array(self) {
            if by.contains(str) {
                out.append(storeStr)
                storeStr.removeAll()
                continue
            }
            storeStr.append(str)
        }
        return out
    }
    
    func componentSeparated1(by: String) -> [String] {
        var separateList: [String] = componentSeparate(by: by).map { "\($0)\(by)" }
        separateList[separateList.count-1].removeLast(by.count)
        return separateList
    }
    
    func componentSeparated2(by: String) -> [String] {
        if self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return [] }
        var separateList: [String] = componentSeparate(by: by).map { "\($0)\(by)" }
        separateList[separateList.count-1].removeLast(by.count)
        return separateList
    }
    
    func componentSeparated3(by: String) -> [String] {
        if self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return [] }
        var separateList: [String] = componentSeparate(by: by).map {"\($0)\(by)"}.filter {$0 != "-"}
        separateList[separateList.count-1].removeLast(by.count)
        return separateList
    }
    
    func componentSeparated4(by: String) -> [String] {
        if self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return [] }
        let separateList: [String] = componentSeparate(by: by).map {"\($0)\(by)"}.filter {$0 != "-"}
        return separateList
    }
}

print("This-is-a-sentence-".componentSeparated1(by: "-"))
print("".componentSeparated2(by: "-"))
print("This-is-a-sentence-".componentSeparated3(by: "-"))
print("This-is-a-sentence-".componentSeparated4(by: "-"))

Output:

["This-", "is-", "a-", "sentence-", ""]
[]
["This-", "is-", "a-", "sentence"]
["This-", "is-", "a-", "sentence-"]

Upvotes: 0

le n
le n

Reputation: 158

You can try this:

var str = "This-is-a-sentence"
var separateList = str.components(separatedBy: "-")
for (index, _) in separateList.enumerated() {
    if index < separateList.count - 1 {
        separateList[index].append("-")
    }
}

print(separateList)

Upvotes: 3

Related Questions