Swift:只在开始时删除string的特定字符

我正在寻找一个答案,但还没有find一个,所以:

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

我的目标是得到一个像这样的“bla#blub”这样的string,否则用replaceOccourencies就会很容易…

我希望你能帮上忙。

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

用法:

 ltrim("#####bla#blub", ["#"]) //->"bla#blub" 
 var str = "###abc" while str.hasPrefix("#") { str.remove(at: str.startIndex) } print(str) 

我最近build立了一个string的扩展,它将从一开始,结束或两者中“清除”一个string,并允许你指定一组你想删除的字符。 请注意,这不会从string内部删除字符,但将其扩展到这样做会相对简单。 (使用Swift 2构build的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 } 

正则expression式解决scheme将是:

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

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