Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 911
Fry Avatar asked Sep 15 '16 15:09

Fry


2 Answers

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"
like image 178
OOPer Avatar answered Sep 21 '22 02:09

OOPer


var str = "###abc"

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

print(str)
like image 33
wint Avatar answered Sep 18 '22 02:09

wint