objective-c 2.0 Mac和iOS开发实践指南 练习(一) 草稿

11.9 练习

1.在NSString上编写一个分类方法,用来将字符串种的单词的顺序反向。反向分类方法应该将字符串“dog bites man”变成字符串“man bites dog”,最初的字符串是接受者,并且反向字符串是方法的返回值。编写一个较小的程序来测试---reverseWords。


//
//  NSString+ReverseWords.h
//  ReverseWords
//
//  Created by Mamong on 12-11-21.
//  Copyright (c) 2012年 Mamong. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSString (ReverseWords)
- (NSString *)reverseWords;

@end

//
//  NSString+ReverseWords.m
//  ReverseWords
//
//  Created by Mamong on 12-11-21.
//  Copyright (c) 2012年 Mamong. All rights reserved.
//

#import "NSString+ReverseWords.h"

@implementation NSString (ReverseWords)
- (NSString *)reverseWords
{
    NSArray *wordList = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *index;
    NSMutableArray *reverseList = [NSMutableArray arrayWithCapacity:4];
    NSString *output;
    for(index in [wordList reverseObjectEnumerator]){
        [reverseList addObject:index];
    }
    output = [reverseList componentsJoinedByString:@" "];
    return output;

}
@end

//
//  main.m
//  ReverseWords
//
//  Created by Mamong on 12-11-21.
//  Copyright (c) 2012年 Mamong. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "NSString+ReverseWords.h"

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

    @autoreleasepool {
        
        // insert code here...
        NSString *string = @"dog bites man";
        NSLog(@"the string before convertion is:%@",string);
        string = [string reverseWords];
        NSLog(@"the string after convertion is:%@",string);
        
    }
    return 0;
}


2012-11-21 14:25:30.099 ReverseWords[1091:303] the string before convertion is:dog bites man
2012-11-21 14:25:30.105 ReverseWords[1091:303] the string after convertion is:man bites dog

你可能感兴趣的:(objective-c 2.0 Mac和iOS开发实践指南 练习(一) 草稿)