Swift:仅在开头删除字符串的特定字符 [英] Swift: Remove specific characters of a string only at the beginning
本文介绍了Swift:仅在开头删除字符串的特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在寻找答案,但还没有找到答案,所以:
i was looking for an answer but haven't found one yet, so:
例如:我有一个字符串,例如 #blablub,我想删除开头的#,我可以简单地删除第一个字符。但是,如果我有一个带有 #### bla#blub的字符串,而我只想只在第一个字符串的开头删除所有的#,我不知道如何解决这个问题。
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.
我的目标是得到像这样的字符串 bla#blub,否则使用replaceOccourencies可以很容易...
My goal is to get a string like this "bla#blub", otherwise it would be to easy with replaceOccourencies...
希望您能提供帮助。
推荐答案
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 ""
}
}
用法:
ltrim("#####bla#blub", ["#"]) //->"bla#blub"
这篇关于Swift:仅在开头删除字符串的特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文