views:

52

answers:

2

The following code works, but it's ugly and creates a bunch of autoreleased objects. I'm using similar code for parsing reserved HTML characters as well (for quotes, & symbols, etc). I'm just wondering... Is there a cleaner way?

    NSString *result = [[NSString alloc] initWithString:userInput];

    NSString *result2 = [result stringByReplacingOccurrencesOfString:@"#" 
                                withString:@"\%23"];
    NSString *result3 = [result2 stringByReplacingOccurrencesOfString:@" " 
                                withString:@"\%20"];
    formatted = [[result3 stringByReplacingOccurrencesOfString:@"&" 
                                withString:@"\%26"] retain];
    [result release];
A: 

Hi,

Have you tried to use the stringByAddingPercentEscapesUsingEncoding method?

formatted = [result stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
Yannick L.
A: 

@Yannick, you were on the right track, thank you. stringByAddingPercentEscapesUsingEncoding sort of works but ignores certain characters that can still be a problem (like slashes). Here is the best way to do URL encoding:

NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                                       NULL,
                                       (CFStringRef)unencodedString,
                                       NULL,
                                       (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                       kCFStringEncodingUTF8 );
Charles S.