简体   繁体   English

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

[英]Swift: Remove specific characters of a string only at the beginning

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.例如:我有一个像“#blablub”这样的字符串,我想删除开头的#,我可以简单地删除第一个字符。 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.但是,如果我有一个带有“#####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.我希望你能帮忙。

Swift2 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 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"
var str = "###abc"

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

print(str)

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

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
    }

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

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

As Martin R already pointed out in a comment above, a regular expression is appropriate here:正如 Martin R 已经在上面的评论中指出的那样,正则表达式在这里是合适的:

myString.replacingOccurrences(of: #"^#+"#, with: "", options: .regularExpression)

You can replace the inner # with any symbol you're looking for, or you can get more complicated if you're looking for one of several characters or a group etc. The ^ indicates it's the start of the string (so you don't get matches for # symbols in the middle of the string) and the + represents "1 or more of the preceding character".您可以将内部#替换为您要查找的任何符号,或者如果您要查找多个字符中的一个或一组等,则可能会变得更复杂。 ^表示它是字符串的开头(因此您不需要' t 获取字符串中间# 符号的匹配项), +表示“1 个或多个前面的字符”。 ( * is 0 or more but there's not much point in using that here.) *是 0 或更多,但在这里使用它没有多大意义。)

Note the outer hash symbols are to turn the string into a raw String so escaping is not needed (though I suppose there's nothing that actually needs to be escaped in this particular example).请注意,外部哈希符号会将字符串转换为原始字符串,因此不需要转义(尽管我认为在此特定示例中实际上没有什么需要转义的)。

To play around with regex I recommend: https://regexr.com/我推荐使用正则表达式: https : //regexr.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM