Swift: Remove specific characters of a string only

2020-04-10 00:35发布

问题:

i was looking for an answer but haven't found one yet, so:

For example: i have a string like "#blablub" and i want to remove the # at the beginning, i can just simply remove the first char. But, if i have a string with "#####bla#blub" and i only want to remove all # only at the beginning of the first string, i have no idea how to solve that.

My goal is to get a string like this "bla#blub", otherwise it would be to easy with replaceOccourencies...

I hope you can help.

回答1:

Swift2

func ltrim(str: String, _ chars: Set<Character>) -> String {
    if let index = str.characters.indexOf({!chars.contains($0)}) {
        return str[index..<str.endIndex]
    } else {
        return ""
    }
}

Swift3

func ltrim(_ str: String, _ chars: Set<Character>) -> String {
    if let index = str.characters.index(where: {!chars.contains($0)}) {
        return str[index..<str.endIndex]
    } else {
        return ""
    }
}

Usage:

ltrim("#####bla#blub", ["#"]) //->"bla#blub"


回答2:

var str = "###abc"

while str.hasPrefix("#") {
    str.remove(at: str.startIndex)
}

print(str)


回答3:

I recently built an extension to String that will "clean" a string from the start, end, or both, and allow you to specify a set of characters which you'd like to get rid of. Note that this will not remove characters from the interior of the String, but it would be relatively straightforward to extend it to do that. (NB built using Swift 2)

enum stringPosition {
    case start
    case end
    case all
}

    func trimCharacters(charactersToTrim: Set<Character>, usingStringPosition: stringPosition) -> String {
        // Trims any characters in the specified set from the start, end or both ends of the string
        guard self != "" else { return self } // Nothing to do
        var outputString : String = self

        if usingStringPosition == .end || usingStringPosition == .all {
            // Remove the characters from the end of the string
            while outputString.characters.last != nil && charactersToTrim.contains(outputString.characters.last!) {
                outputString.removeAtIndex(outputString.endIndex.advancedBy(-1))
            }
        }

        if usingStringPosition == .start || usingStringPosition == .all {
            // Remove the characters from the start of the string
            while outputString.characters.first != nil && charactersToTrim.contains(outputString.characters.first!) {
                outputString.removeAtIndex(outputString.startIndex)
            }
        }

        return outputString
    }


回答4:

A regex-less solution would be:

func removePrecedingPoundSigns(s: String) -> String {
    for (index, char) in s.characters.enumerate() {
        if char != "#" {
            return s.substringFromIndex(s.startIndex.advancedBy(index))
        }
    }
    return ""
}


回答5:

A swift 3 extension starting from OOPer's response:

extension String {
    func leftTrim(_ chars: Set<Character>) -> String {
        if let index = self.characters.index(where: {!chars.contains($0)}) {
            return self[index..<self.endIndex]
        } else {
            return ""
        }
    }
}