一聚教程网:一个值得你收藏的教程网站

热门教程

iOS 判断字符串是否包含空格

时间:2022-06-25 23:33:23 编辑:袖梨 来源:一聚教程网

有时候需要对注册,登录,忘记密码的密码进行是否包含空格进行判断
我就自己封装了一个方法,可以根据返回的bool值进行判断

-(BOOL)isEmpty:(NSString *) str {
    NSRange range = [str rangeOfString:@" "];
    if (range.location != NSNotFound) {
        return  YES; //yes代表包含空格
    }else {
        return  NO;  //反之
    }
}

例子

NSString *_string = [NSString stringWithFormat:@"123 456"];
NSRange _range = [_string rangeOfString:@" "];
if (_range.location != NSNotFound) {
      //有空格
}else {
      //没有空格
}

例子

//判断内容是否全部为空格  yes 全部为空格  no 不是
+ (BOOL) isEmpty:(NSString *) str {
    
    if (!str) {
        return true;
    } else {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

热门栏目