在面试中,经常被问到字符串倒序的面试题,下面提供两种简单的实现:
第一种:
- (NSString*)reverseWordsInString:(NSString*)oldStr{
NSMutableString *newStr = [[NSMutableString alloc] initWithCapacity:oldStr.length];
for (int i = (int)oldStr.length - 1; i >= 0; i --) {
unichar character = [oldStr characterAtIndex:i];
[newStr appendFormat:@"%c",character];
}
return newStr;
}
第二种:
- (NSString*)reverseWordsInString:(NSString*)oldStr
{
NSMutableString *newStr = [NSMutableString stringWithCapacity:oldStr.length];
[str enumerateSubstringsInRange:NSMakeRange(0, oldStr.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
[newStr appendString:substring];
}];
return newStr;
}