在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
内容大纲:1、需求 2、源代码 3、附录
需求使用Category给NSString类增加以下功能(需要用到的方法自己查资料或者猜)
在直接看源代码之前,先大致讲讲该代码的有价值的地方:
源代码main.m 1 #import <Foundation/Foundation.h> 2 #import "NSString+calNum.h" 3 4 int main(int argc, const char * argv[]) { 5 @autoreleasepool { 6 7 //测试1 8 NSString *str1 = @"324fdsfk656HF99Jp"; 9 NSLog(@"%d",[str1 getNumCount]); 10 11 //测试2 12 NSString* str2 = @"abc"; 13 NSLog(@"%@",[str2 getRever]); 14 15 //测试3 16 NSString* str3 = @" jack rose "; 17 NSLog(@"|%@|",[str3 removeSpace]); 18 19 //测试4 20 NSString* str4 = @"http://www.baidu.com"; 21 NSLog(@"%@",[str4 sub]); 22 } 23 return 0; 24 } NSString+calNum.h 1 #import <Foundation/Foundation.h> 2 3 @interface NSString (calNum) 4 5 -(int)getNumCount; 6 7 -(NSString *)getRever; 8 //3> 去除字符串两端空格(比如@" jack rose "调用方法后返回@"jack rose") 9 10 -(NSString*)removeSpace; 11 12 //4> 截取网站域名中www.和.com之间的字符串(比如@"http://www.baidu.com"调用方法返回@"baidu") 13 -(NSString*)sub; 14 15 -(NSString*)removeLRSpace; 16 17 @end NSString+calNum.m 1 #import "NSString+calNum.h" 2 3 @implementation NSString (calNum) 4 5 -(int)getNumCount{ 6 int count = 0; 7 int length = (int)[self length]; 8 9 for (int i = 0; i<length; i++) { 10 unichar c = [self characterAtIndex:i]; 11 if (c>='0' && c<='9') { 12 count ++; 13 } 14 } 15 return count; 16 17 } 18 19 -(NSString *)getRever{ 20 uint64_t i = 0; 21 uint64_t j = [self length]-1; 22 23 unichar *character = malloc(sizeof([self characterAtIndex:0])*self.length); 24 25 while (i<j) { 26 character[i] = [self characterAtIndex:j]; 27 character[j] = [self characterAtIndex:i]; 28 29 i++; 30 j--; 31 } 32 if (i == j) { 33 character[i] = [self characterAtIndex:i]; 34 } 35 return [NSString stringWithCharacters:character length:[self length]]; 36 37 } 38 39 40 -(NSString *)removeSpace{ 41 uint64_t length = [self length]; 42 int len = 0; 43 unichar *character = malloc((sizeof([self characterAtIndex:0])*self.length)); 44 unichar c ; 45 int i= 0; 46 while (i<length) { 47 c = [self characterAtIndex:i]; 48 if (c!=' ') { 49 character[len] = [self characterAtIndex:i]; 50 len++; 51 } 52 i++; 53 } 54 55 return [NSString stringWithCharacters:character length:len+1]; 56 } 57 58 59 //4> 截取网站域名中www.和.com之间的字符串(比如@"http://www.baidu.com"调用方法返回@"baidu") 60 -(NSString *)sub{ 61 NSString* str = [[self substringFromIndex:11] substringToIndex:5]; 62 63 return str; 64 } 65 66 -(NSString *)removeLRSpace{ 67 return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 68 } 69 70 @end
附录http://nshipster.cn/nscharacterset/
|
请发表评论