0

I would like to reverse a sentence, but I dont know how I can get the next object correctly in fast enumeration without any problem :/

- (NSString *) reverseWords
{
    NSString    *result = [[NSString alloc] init];
    NSArray     *tab_words = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSEnumerator    *reversed = [tab_words reverseObjectEnumerator];
    for (NSString *word in reversed)
    {
        result = [result stringByAppendingString:word];
        // Bug here
        if ([reversed nextObject])
            result = [result stringByAppendingString:@" "];
    }
    return (result);
}

Thx you

Marc Lamberti
  • 763
  • 2
  • 9
  • 24

2 Answers2

1

There is an easier way to reverse the sentence than enumerating through it. You can get the reversed array and then join it together with a space (using the componentsJoinedByString: method) to produce another NSString

- (NSString *) reverseWords
{
    NSArray *tab_words  = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSArray *reversed   = [[tab_words reverseObjectEnumerator] allObjects];
    NSString *result    = [reversed componentsJoinedByString:@" "];
}   
Suhail Patel
  • 13,644
  • 2
  • 44
  • 49
  • thx you, but if i want to know if the next object in fast enumeration is null or not, How i do that ? Because, when i call nextObjet, the enumerator is changed :s – Marc Lamberti Jun 21 '12 at 15:31
  • Calling nextObject does change the enumerator. A potential solution would be to call allObjects within the for loop whilst enumerating because that will give you all the remaining objects. If you want to see if all the objects have been enumerated then you'll get back an empty or nil array – Suhail Patel Jun 21 '12 at 15:40
0

I suggest reversing the array and then using NSArray's componentsJoinedByString: method. For quick reference on reversing an array, this SO question

This is very similar to your existing code, with the simple added step of using your existing loop to build an intermediary array. Then add the final componentsJoinedByString call to get the return string.

Community
  • 1
  • 1
Chris Trahey
  • 18,202
  • 1
  • 42
  • 55