- (void)viewDidLoad {
[super viewDidLoad];
[self numOne:11];
}
//某个整数中1出现的次数
-(void)numOne:(NSInteger )n{
int count=0;
for (int i=1; i<=n ; i++) {
NSString *str=[NSString stringWithFormat:@"%d",i];
NSLog(@"str=====:%@",str);
BOOL isOne=[str containsString:@"1"];
if (isOne) {
count++;
}
NSLog(@"有“1”的数的个数:%d",count);
}
注意:containsString 是8.0之后才有的API 你手机系统低于8.0肯定会出错的。
iOS 7 containsstring的实现方法如下:
- (BOOL)containsString:(NSString *)aString NS_AVAILABLE(10_10, 8_0){
if (IS_BLANK_STRING(aString)) {
return NO;
}
if ([self rangeOfString:aString].location != NSNotFound) {
return YES;
}
return NO;
}
网友评论