美文网首页
NSString 去空白字符

NSString 去空白字符

作者: 公爵海恩庭斯 | 来源:发表于2017-03-27 14:10 被阅读83次

    去除字符串左右两边的空白是比较通用的代码逻辑:

    @interface NSString (Strip)
    
    - (NSString *)wbt_trimmedString;
    - (NSString *)wbt_leftTrimmedString;
    - (NSString *)wbt_rightTrimmedString;
    
    @end
    
    @implementation NSString (Strip)
    
    /* Returns a new string made by removing from start of the receiver whitespace and newline characters */
    - (NSString *)wbt_leftTrimmedString
    {
        NSRange range = [self rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet].invertedSet];
    
        return [self substringFromIndex:range.location];
    }
    
    /* Returns a new string made by removing from end of the receiver whitespace and newline characters */
    - (NSString *)wbt_rightTrimmedString
    {
        NSRange range = [self rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet].invertedSet options:NSBackwardsSearch];
        
        return [self substringToIndex:range.location];
    }
    
    /* Returns a new string made by removing from both ends of the receiver whitespace and newline characters */
    - (NSString *)wbt_trimmedString
    {
        return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:NSString 去空白字符

          本文链接:https://www.haomeiwen.com/subject/ymlrottx.html