The way in which strings are reversed in OC can be handled in two ways:
The first one: remove each character from the string from beginning to end, then add it from the tail to the variable string, and then output it.
The second is to convert a string inside the OC to a string in the C language, then dynamically assign an array, and then copy the contents of the string into the array for the end-to-end exchange operation. Total array length/2 operations.
Mode one: OC version
1 -(NSMutableString*)Reverse
2 {
3 NSUInteger length = [self length];
4 NSMutableArray *array = [NSMutableArray arrayWithCapacity:length];
5
6 for(long i=length-1; i>=0; i--)
7 {
8 unichar c = [self characterAtIndex:i];
9 [array addObject:[NSString stringWithFormat:@"%c",c]];
10 }
11
12
13 NSMutableString *str = [NSMutableString stringWithCapacity:length];
14 for(int i=0; i<=length-1; i++)
15 {
16 [str appendString:array[i]];
17 }
18 return str;
19 }@end
Mode two: C language version
1 @implementation NSString (Reverse)
2 -(NSMutableString*)Reverse
3 {
4 const char *str = [self UTF8String];
5 NSUInteger length = [self length];
6 char *pReverse = (char*)malloc(length+1);//Dynamic allocation of space
7 strcpy(pReverse, str);
8 for(int i=0; i<length/2; i++)
9 {
10 char c = pReverse[i];
11 pReverse[i] = pReverse[length-i-1];
12 pReverse[length-i-1] = c;
13}
14 NSMutableString *pstr = [NSMutableString stringWithUTF8String:pReverse];
15 free(pReverse);
16 return pstr;
17}
18 @end
Main function test:
1 // main.m
2 // Reverse of string
3 //
4 // Created by ma c on 15/8/18.
5 // Copyright (c) 2015 bjsxt. All rights reserved.
6 //
7
8 #import <Foundation/Foundation.h>
9 #import "NSString+Reverse.h"
10 int main(int argc, const char * argv[])
11 {
12 @autoreleasepool
13 {
14 NSMutableString *string = [NSMutableString stringWithFormat:@"XYQ-CHINA"];
15 NSString *str = [NSString stringWithString:[string Reverse]];
16 NSLog(@"%@",str);
17}
18 return 0;
19}
The test results are as follows:
2015-08-18 19:42:56.696 Reversal of string [2222:136571] ANIHC-QYX
Program ended with exit code: 0
Objective-c: Inverse of string reverse