用分类实现前缀后缀添加

           我特别喜欢分类,而它的确是处理一些小问题的好帮手,在本例中使用分类来实现给一个NSString添加前后缀的方法。代码简单,就不多说了,可以帮助初学者掌握分类的使用方法。



//
//  NSString+PrefixAndSuffix.h
//  AddPrefixAndSuffix
//
//  Created by Mamong on 13-1-11.
//  Copyright (c) 2013年 Mamong. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSString (PrefixAndSuffix)

- (NSString *)addPrefix:(NSString *)prefix;
- (NSString *)addSuffix:(NSString *)suffix;
@end

//
//  NSString+PrefixAndSuffix.m
//  AddPrefixAndSuffix
//
//  Created by Mamong on 13-1-11.
//  Copyright (c) 2013年 Mamong. All rights reserved.
//

#import "NSString+PrefixAndSuffix.h"

@implementation NSString (PrefixAndSuffix)
- (NSString *)addPrefix:(NSString *)prefix{
    self = [NSString stringWithFormat:@"%@%@",prefix,self];
    return self;
}
- (NSString *)addSuffix:(NSString *)suffix{
    self = [NSString stringWithFormat:@"%@%@",self,suffix];
    return self;
}
@end

//
//  main.m
//  AddPrefixAndSuffix
//
//  Created by Mamong on 13-1-11.
//  Copyright (c) 2013年 Mamong. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "NSString+PrefixAndSuffix.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        NSString *oldString = @"nice";
        NSString *newString =[oldString addPrefix:@"Man"];
        NSString *newString2 = [oldString addSuffix:@"Man"];
        NSLog(@"%@,%@",newString,newString2);
        
    }
    return 0;
}


2013-01-11 14:15:16.447 AddPrefixAndSuffix[554:303] Mannice,niceMan


你可能感兴趣的:(用分类实现前缀后缀添加)