How to change or reverse the position of words in a String object in Objective C?
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 开发者_Go百科work for any string. Please help. Thanks :)
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]];
}
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
NSString *myStr = @"India is my Country";
NSArray* array= [myStr componentsSeparatedByString:@" " ];
NSArray* reversedArray = [[array reverseObjectEnumerator] allObjects];
NSLog(@"%@",reversedArray);
NSString * result = [reversedArray componentsJoinedByString:@" "];
NSLog(@"%@",result);
精彩评论