#import <Foundation/Foundation.h>
@interface NSString (ReverseString)
-(id)reverseString;//字符串反向输出
#import "NSString+ReverseString.h"
@implementation NSString (ReverseString)
-(id)reverseString
{
NSUInteger len = [self length];
NSMutableString *retStr = [NSMutableStringstringWithCapacity:len];
while (len>0) {
unichar c = [self characterAtIndex:--len];
NSString *s = [NSString stringWithFormat:@"%C", c];
[retStr appendString:s];
}
return retStr;
}
-(void)test
{
NSString *str = @"hello world!";
NSString *retString = [str reverseString];
NSLog(@"retString: %@", retString);
本文介绍如何通过Objective-C中的类别(Category)为现有类添加新方法。以NSString为例,展示了如何为其添加一个字符串反向输出的方法,并提供了完整的代码实现。
391

被折叠的 条评论
为什么被折叠?



