有時候需要對注冊,登錄,忘記密碼的密碼進行是否包含空格進行判斷
我就自己封裝了一個方法,可以根據返回的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;
}
}
}