本文共 1830 字,大约阅读时间需要 6 分钟。
内容大纲:
已知一个字符串,要求找出字符串中所有的阿拉伯数字并计算其个数 例如@"a123sb23r2jsowsalwf"求数字的个数 1、计数器思想,定义一个变量保存结果 2、遍历字符串,取出字符串中所有的字符
1 #import2 3 int getStrCount(NSString* str) 4 { 5 int count = 0; 6 for (int i = 0; i < str.length; i++) { 7 unichar c = [str characterAtIndex:i]; 8 if (c >= '0' && c <= '9') { 9 count++;10 }11 }12 return count;13 }14 15 int main(int argc, const char * argv[]) {16 @autoreleasepool {17 NSString* str = @"a123sb23r2jsowsalwf";18 NSLog(@"%d",getStrCount(str));19 }20 return 0;21 }
思路:因为是计算NSString对象的数字的个数,所以可以通过类别,将这个计算的功能作为NSSting的拓展方法。
创建NSString+getStrCount的类别
1 #import2 3 @interface NSString (getStrCount)4 5 +(int)getStrCount:(NSString*)str;6 7 @end
1 #import "NSObject+getStrCount.h" 2 3 @implementation NSString (getStrCount) 4 5 +(int)getStrCount:(NSString*)str{ 6 int count = 0; 7 for (int i = 0; i < str.length; i++) { 8 unichar c = [str characterAtIndex:i]; 9 if (c >= '0' && c <= '9') {10 count++;11 }12 }13 return count;14 }15 16 @end
然后在客户端:
1 int main(int argc, const char * argv[]) {2 @autoreleasepool {3 NSString* str = @"a123sb23r2jsowsalwf";4 NSLog(@"%d",[NSString getStrCount:str]);5 }6 return 0;7 }
NSString+getStrCount类别中
1 #import2 3 @interface NSString (getStrCount)4 5 -(int)count;6 7 @end
1 #import "NSObject+getStrCount.h" 2 3 @implementation NSString (getStrCount) 4 5 -(int)count{ 6 int count = 0; 7 for (int i = 0; i < self.length; i++) { 8 unichar c = [self characterAtIndex:i]; 9 if (c >= '0' && c <= '9') {10 count++;11 }12 }13 return count;14 }15 @end
然后在客户端:
1 int main(int argc, const char * argv[]) {2 @autoreleasepool {3 NSString* str = @"a123sb23r2jsowsalwf";4 NSLog(@"%d",[str count]);5 }6 return 0;7 }
转载地址:http://kmhtl.baihongyu.com/