Simple Pig Latin

2017/12/27 posted in  codeWars

一开始的复杂版:

#import <Foundation/Foundation.h>

NSString *pigIt(NSString *s) {
    NSMutableArray *str = [s componentsSeparatedByString:@" "].mutableCopy;
    NSMutableString *res = @"".mutableCopy;
    for (NSString *tmp in str) {
        unichar c = [tmp characterAtIndex:0];
        if ((c>='a'&&c<='z')||(c>='A'&&c<='Z')) {
            NSMutableString *change = tmp.mutableCopy;
            [change appendFormat:@"%c",c];
            if ([tmp isEqualToString:[str lastObject]]) {
                [change appendString:@"ay"];
            }else{
                [change appendString:@"ay "];
            }
            [res appendString:[change substringFromIndex:1]];
        }else{
            [res appendFormat:@"%c",c];
        }
    }
    return res;
}

简化版

#import <Foundation/Foundation.h>

NSString *pigIt(NSString *s) {
  NSMutableArray *result = [s componentsSeparatedByString: @" "];
  for (size_t i = 0; i < [result count]; i++) result[i] = [[[result[i] substringFromIndex: 1] stringByAppendingString: [result[i] substringToIndex: 1]] stringByAppendingString: @"ay"];
  return [result componentsJoinedByString: @" "];
}