在目标中反转一个字符串

时间:2013-09-27 15:31:25

标签: objective-c string nsstring reverse

我是编码和目标的新手。我知道有很多类似的问题,但我想知道为什么我的解决方案不起作用。

我为自己创建了一个简单的挑战:将用户键入的字符串反转为textField,并将反向字符串显示到控制台。但是这段代码不起作用,没有错误,通知。

似乎reversedString没有收到任何东西。

- (IBAction)countString:(id)sender {
    NSString *string = [textField stringValue];
    NSUInteger count = [string length];
    [countView setStringValue:[NSString stringWithFormat:@"%@\n%lu", string, (unsigned long)count]];
    // Challenge starts here
    NSMutableString *reversedString = [[NSMutableString alloc] initWithFormat:@""];
    for (NSInteger i = [string length] - 1; i >= 0; i--) {
        NSLog(@"%li", (long)i);
        unichar abc = [string characterAtIndex:i];
        NSString *charString = [NSString stringWithFormat:@"%c", abc];
        [reversedString stringByAppendingString:charString];
    }
    NSLog(@"%@", reversedString);
}

2 个答案:

答案 0 :(得分:0)

stringByAppendingString:会返回一个新的NSString,并且在您的代码中会忽略返回值,因为您使用的是NSMutableString,请替换

[reversedString stringByAppendingString:charString];

[reversedString appendString:charString];

答案 1 :(得分:0)

对任何对象使用方法:NSString,NSNumber等。:

NSLog(@"%@",[self reverseObject:@12345]);
NSLog(@"%@",[self reverseObject:@"Hello World"]);

方法:

-(NSString*)reverseObject:(id)string{

string = [NSString stringWithFormat:@"%@",string];
NSMutableString *endString = [NSMutableString new];

while ([string length]!=[endString length]) {
NSRange range = NSMakeRange([string length]-[endString length]-1, 1);
[endString appendString: [string substringWithRange:range]];
}
return endString;
}

日志:

2014-04-16 11:20:25.312 TEST [23733:60b] 54321 2014-04-16 11:20:25.313 TEST [23733:60b] dlroW olleH