Escaping all control characters in a NSString

Tue. January 3, 2012
Categories: NSString, Objective-C, Python
Tags: , , , , ,

Here is a category that will mimic the functionality of the built-in python repr function for strings:

- (NSString *)repr {
    NSMutableString *myRepr = [[NSMutableString alloc] initWithString:self];
    NSRange myRange = NSMakeRange(0, [self length]);
    NSArray *toReplace = [NSArray arrayWithObjects:@"\0", @"\a", @"\b", @"\t", @"\n", @"\f", @"\r", @"\e", nil];
    NSArray *replaceWith = [NSArray arrayWithObjects:@"\\0", @"\\a", @"\\b", @"\\t", @"\\n", @"\\f", @"\\r", @"\\e", nil];
    for (int i = 0, count = [toReplace count]; i < count; ++i) {
         [myRepr replaceOccurrencesOfString:[toReplace objectAtIndex:i] withString:[replaceWith objectAtIndex:i] options:0 range:myRange];
     }
     NSString *retStr = [NSString stringWithFormat:@"\"%@\"", myRepr];
     [myRepr release];
     return retStr;
 }

Normally, this:

NSString *myString = @"SOME STRING WITH \n NEWLINES, \t TABS, ETC...\n\t..\n.....\n\tTAB";
NSLog("%@", myString);

would print:

SOME STRING WITH 
 NEWLINES,      TABS, ETC...
    ..
.....
    TAB

With repr:

NSString *myString = @"SOME STRING WITH \n NEWLINES, \t TABS, ETC...\n\t..\n.....\n\tTAB";
NSLog("%@", [myString repr]);

You can see all of the literal characters:

"SOME STRING WITH \n NEWLINES, \t TABS, ETC...\n\t..\n.....\n\tTAB"

The array of control characters is taken from en.wikipedia.org/wiki/Control_character

Download Category: NSString+JH.tar.gz

Comments

Leave a Reply