在Objective-C中,检测一个或多个空格的方法如下:
NSString *string = @"Hello World ";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\s+" options:0 error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
BOOL hasSpaces = (matches.count > 0);
rangeOfString
方法NSString *string = @"Hello World ";
NSRange range = [string rangeOfString:@" "];
BOOL hasSpaces = (range.location != NSNotFound);
componentsSeparatedByString
方法NSString *string = @"Hello World ";
NSArray *components = [string componentsSeparatedByString:@" "];
BOOL hasSpaces = (components.count > 1);
以上三种方法都可以用于检测一个或多个空格。如果需要检测其他空白字符,可以使用正则表达式的\\s
表示空白字符。
领取专属 10元无门槛券
手把手带您无忧上云