Swift:仅在开头删除字符串的特定字符

时间:2023-01-19 20:22:16

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.

例如:我有一个像“#blablub”这样的字符串,我想在开头删除#,我只需删除第一个字符。但是,如果我有一个带有“##### bla #blub”的字符串,我只想在第一个字符串的开头删除所有#,我不知道如何解决这个问题。

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

我的目标是得到一个像这样的字符串“bla#blub”,否则就可以轻松使用replaceOccourencies ......

I hope you can help.

我希望你能帮忙。

5 个解决方案

#1


6  

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


4  

var str = "###abc"

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

print(str)

#3


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)

我最近构建了一个String的扩展,它将从开头,结尾或两者中“清理”一个字符串,并允许你指定一组你想要删除的字符。请注意,这不会从String的内部删除字符,但扩展它来执行此操作会相对简单。 (NB使用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


0  

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


0  

A swift 3 extension starting from OOPer's response:

从OOPer的回复开始的快速3扩展:

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

#1


6  

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


4  

var str = "###abc"

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

print(str)

#3


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)

我最近构建了一个String的扩展,它将从开头,结尾或两者中“清理”一个字符串,并允许你指定一组你想要删除的字符。请注意,这不会从String的内部删除字符,但扩展它来执行此操作会相对简单。 (NB使用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


0  

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


0  

A swift 3 extension starting from OOPer's response:

从OOPer的回复开始的快速3扩展:

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