1

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

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Note that this would require Foundation. Not native Swift. This would also result in [""] is the original string is empty.
It will also add an empty string to the result if the string ends with "-"
Btw for index in separateList.indices.dropLast() {
0

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

3 Comments

This would result in "-" is it is an empty string
This will result in the same string plus "-" if it doesn't find any "-"
Note that components(separatedBy:) is a Foundation method. Not native Swift. It probably doesn't matter to the OP but it is worth mentioning for future readers. BTW None of your methods returns ["This-", "is-", "a-", "sentence-"]

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.