天天看點

Objective-c - 非正式協定

#import <Foundation/Foundation.h>

#pragma mark -

#pragma mark 非正式協定:#import "NSString+YYCount.h"

//聲明

@interface NSString (YYCount)

//為NSString類添加的分類中添加一個方法實作統計一個字元串資料中的阿拉伯數字的個數

- (int)countForNum;

@end

//實作

@implementation NSString (YYCount)

//為NSString類添加的分類中添加一個方法實作統計一個字元串資料中的阿拉伯數字的個數

- (int)countForNum

{

    int count = 0;

    for(int i = 0; i < self.length; i++)

    {

        unichar ch = [self characterAtIndex:i];

        if(ch >= '0' && ch <= '9')

        {

            count++;

        }

    }

    return count;

}

@end

#pragma mark -

#pragma mark main函數

int main(int argc, const char * argv[]) {

    //建立一個oc字元串

    NSString *str = @"sdhgaj1ghjgj2hghj3jhghj4ghjg5jhgj6";

    int count = [str countForNum];

    NSLog(@"count = %d", count);

    return 0;

}