使用Objective-C以相反的顺序打印单词或给定的字母?

时间:2017-01-07 13:33:27

标签: objective-c

我是Objective-C的新手。 如何使用Objective-C以相反的顺序打印单词或给定的字母? 我在NSLog中给出的文本应该以相反的顺序显示。 Exp:“你好”应该显示“olleH”。

2 个答案:

答案 0 :(得分:0)

请试试这个

- (NSString *)reverseOfString : (NSString *)Str {
int strLength = (int)[Str length];
NSMutableString *reverseString = [[NSMutableString alloc] initWithCapacity:strLength];
for(int i=strLength-1; i>=0; i--)
[reverseString appendString:[NSString stringWithFormat:@"%c",[Str characterAtIndex:i]]];
return reverseString;

}

答案 1 :(得分:0)

或者对于一个较短的递归方法(虽然对于很长的字符串来说效率很低)但只是为了让你有另一种方法:

-(NSString *) reverseString: (NSString *) word{
    if([word length] == 1)
        return word;
return [NSString stringWithFormat:@"%@%@",[word substringWithRange: NSMakeRange([word length]-1,1)],[self reverseString:[word substringWithRange: NSMakeRange(0,[word length]-1)]]];
}
相关问题