objective-c 2.0 MacとiOS開発実践ガイド練習(一)下書き

2009 ワード

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