main()函数的内容为:
#import <Foundation/Foundation.h> #import "NSString+countNum.h" int main() { NSString *str=@"sadhe123123ada"; //调用NSString的扩展方法:countNumForString; [str countNumForString]; return 0; } 在创建一个NSString类的扩展类(countNum): .h文件中的内容为: #import <Foundation/Foundation.h> //扩展方法的声明: @interface NSString (countNum)
-(void)countNumForString;
@end .m文件中的内容为:
#import "NSString+countNum.h" 扩展方法的实现: @implementation NSString (countNum) -(void)countNumForString{ int count=0; for (int i=0;i<self.length;i++) { unichar ch= [self characterAtIndex:i]; if (ch>='0'&&ch<='9') { count++; } } NSLog(@"%@数字的个数为%d",self,count);
} @end
|