Trim spaces from end of a NSString

前端 未结 14 1151
既然无缘
既然无缘 2020-11-27 09:26

I need to remove spaces from the end of a string. How can I do that? Example: if string is \"Hello \" it must become \"Hello\"

14条回答
  •  孤城傲影
    2020-11-27 09:36

    Swift version

    Only trims spaces at the end of the String:

    private func removingSpacesAtTheEndOfAString(var str: String) -> String {
        var i: Int = countElements(str) - 1, j: Int = i
    
        while(i >= 0 && str[advance(str.startIndex, i)] == " ") {
            --i
        }
    
        return str.substringWithRange(Range(start: str.startIndex, end: advance(str.endIndex, -(j - i))))
    }
    

    Trims spaces on both sides of the String:

    var str: String = " Yolo "
    var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    

提交回复
热议问题