Reverse string function


#1

I wrote a little function to reverse a string, it works fine, but I run into a problem when
I try to reverse a string which was read from a file - then I get nothing but a blank. I can not
figure out my mistake :frowning: - maybe someone can push me in the right direction.

[code]#import <Foundation/Foundation.h>

NSString * reverseString(NSString *string)
{
NSMutableString *reverseString = [NSMutableString string];

if ([string length] > 1) {
    for (NSUInteger i = [string length]; i > 0; i--) {
        [reverseString appendString:[string substringWithRange:NSMakeRange(i-1, 1)]];
    }
    return reverseString;
}
return string;

}

int main (int argc, const char * argv[])
{
@autoreleasepool {

    NSFileHandle *file;
    file = [NSFileHandle fileHandleForReadingAtPath:@"/file"];
    NSString *str = [[NSString alloc] initWithData:[file readDataOfLength:4] encoding:NSUTF8StringEncoding];
    NSLog(@"Reverse string: %@", reverseString(str));  // this does not work, I get just a blank
                                                       //without the reverseString() I get the correct string
    NSLog(@"Frankfurt reverse: %@", reverseString(@"Frankfurt")); // this works
    [file closeFile];

}
return 0;

}
[/code]
Thanks in advance
Vertex


#2

I solved it by my own. It was a little bit weird, because I have handled the file data the wrong way. If I replaceNSString *str = [[NSString alloc] initWithData:[file readDataOfLength:4] encoding:NSUTF8StringEncoding];with:

NSString *str = [NSString stringWithUTF8String:[[file readDataOfLength:4] bytes]];it works as expected.

cu
Vertex


#3

Where is this in the Chapter 5 of the book?

:confused:

What is a reverse string?


#4

I think he was just having fun. Keep going. Fret not.