On Thu, Feb 5, 2009 at 4:52 PM, Iceberg-Dev <dev.iceb...@gmail.com> wrote: > Problem: > -------- > > I would like to transform a NSString to a NSString conforming to the C > string format. > > Examples: > --------- > > toto -> toto > > "toto -> \"toto > > toto -> toto\ntiti > titi
Well, first consider how you want to handle non-ascii characters. That is, do you want your C string to be in a specific coding, like UTF8. Then, I'd do something like this: const char* cSource = [source cStringUsingEncoding:NSUTF8StringEncoding]; int i = 0, j = 0; int cSourceLen = strlen( cSource ); char *cResult = NULL; NSString *result = nil; cResult = (char*)calloc( (cSourceLen * 4) + 1, 1 ); // max possible for (i = 0; i < cSourceLen; ++i) { if (isprint( cSource[ i ] )) { cResult[ ++j ] = cSource[ i ]; } else { switch (cSource[ i ]) { case '\n': strcpy( cResult[ j ], "\\n" ); j += 2; break; case '\t': // etc for the all the other special cases default: sprintf( cResult[ j ], "\\x%02x", cSource[ i ] ); j += 4; break; } } } result = [[NSString alloc] initWithBytesNoCopy:cResult length:j encoding:NSASCIIStringEncoding freeWhenDone:YES]; That is 100% untested, btw. I have a meeting to go to :) _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com