oc60--Category 分類 練習
阿新 • • 發佈:2017-08-26
i++ 結果 tin -- self. log per sel dex
// main.m // Category練習 #import <Foundation/Foundation.h> #import "NSString+NJ.h" //看不到NSString的.h文件。 /* int countWithStr(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; }*/ int main(int argc, const char * argv[]) { /* 已知一個字符串, 要求找出字符串中所有的阿拉伯數字 @"a123jj46kfd5jlwf7ld"; 1.計數器思想, 定義一個變量保存結果 2.遍歷字符串, 取出字符串中所有的字符 */ NSString *str = @"a1jj46kf1d5jlwf7l9d8"; /* // unichar c = [str characterAtIndex:1]; // NSLog(@"%c", c); int count = 0; for (int i = 0; i < str.length; ++i) { unichar c = [str characterAtIndex:i]; // NSLog(@"%c", c); if (c >= ‘0‘ && c <= ‘9‘) { count++; } }*/ int count2 = countWithStr(str); int count1 = [NSString countWithStr:str]; int count = [str count]; NSLog(@"count = %i", count); return 0; }
// NSString+NJ.h #import <Foundation/Foundation.h> @interface NSString (NJ) + (int)countWithStr:(NSString *)str; - (int)count;@end
// NSString+NJ.m #import "NSString+NJ.h" @implementation NSString (NJ) -(int)countWithStr:(NSString *)str{ int count=0; for (int i=0; i< str.length; i++) { unichar c=[str characterAtIndex:i]; if (c>=‘0‘&& c<=‘9‘) { count++; } } } -(int)count{ int number=0; for (int i= 0; i< self.length; ++i) { unichar c=[self characterAtIndex:i]; if(c>=‘0‘&& c<=‘0‘); number ++; } } @end
// Person.h #import <Foundation/Foundation.h> @interface Person : NSObject - (void)test; @end
// Person.m #import "Person.h" #import "NSString+NJ.h" @implementation Person -(void)test{ NSString *str=@"fds64jkl43fjdslkf"; int count =[NSString countWithStr:str]; NSLog(@" count= %i",count); } @end
oc60--Category 分類 練習