OC开发之——分类应用(32)

一 概述

  1. 给NSString增加一个类方法:计算某个字符串中阿拉伯数字的个数
  2. 给NSString增加一个对象方法:计算当前字符串中阿拉伯数字的根数

二 应用代码

2.1 NSString+Number.h

1
2
3
4
5
#import <Foundation/Foundation.h>
@interface NSString (Number)
+(int)numberCountOfString:(NSString *)str;
-(int)numberCount;
@end

2.2 NSString+Number.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#import "NSString+Number.h"

@implementation NSString (Number)
+(int)numberCountOfString:(NSString *)str
{
// int count=0;
// for (int i=0; i<str.length; i++) {
// UniChar c=[str characterAtIndex:i];
// if(c>='0'&&c<='9')
// {
// count++;
// }
// }
// return count;
return [str numberCount];
}
-(int)numberCount
{
int count=0;
for (int i=0; i<self.length; i++) {
UniChar c=[self characterAtIndex:i];
if(c>='0'&&c<='9')
{
count++;
}
}
return count;
}
@end

2.3 main.m

1
2
3
4
5
6
7
8
9
10
11
12
#import <Foundation/Foundation.h>
#import "NSString+Number.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
int count=[NSString numberCountOfString:@"fafae2323256fgsgga"];
NSLog(@"%d",count);
int count2=[@"fafae2323256fgsgga" numberCount];
NSLog(@"%d",count2);
}
return 0;
}