Reputation: 3
Like for example : To Create a string object with string "Welcome to objective-C" and then to Print the string in as "objective-C to Welcome" This should work for any string. Please help. Thanks :)
Upvotes: 0
Views: 3270
Reputation: 11
NSString *myStr = @"India is my Country";
NSArray* array= [myStr componentsSeparatedByString:@" " ];
NSArray* reversedArray = [[array reverseObjectEnumerator] allObjects];
NSLog(@"%@",reversedArray);
NSString * result = [reversedArray componentsJoinedByString:@" "];
NSLog(@"%@",result);
Upvotes: 0
Reputation: 7899
Here you go. Not the most efficient solution but does his work.
NSString *myString = @"This is a test";
NSArray *myWords = [myString componentsSeparatedByString:@" "];
// myWords is now: [@"This", @"is", @"a", @"test"]
NSMutableArray *reversed = [NSMutableArray arrayWithCapacity:[myWords count]];
NSEnumerator *enumerator = [myWords reverseObjectEnumerator];
for (id element in enumerator) {
[reversed addObject:element];
}
NSString *reverseString = [reversed componentsJoinedByString:@" "];
NSLog(@"%@", reverseString);
If you have any question let me know.
Update
You can try just a simple for cycle. Like this.
NSString *myString = @"This is a test";
NSArray *myWords = [myString componentsSeparatedByString:@" "];
NSMutableString* theString = [NSMutableString string];
for (int i=[myWords count]-1; i>=0;i--){
[theString appendFormat:@"%@ ", [myWords objectAtIndex:i]];
}
Upvotes: 4
Reputation: 1890
Possibly, I think you should read a string till you encounter a space and store it in array and then use- (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2
Upvotes: 0