• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: How to transform a NSString to a NSString C string format?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to transform a NSString to a NSString C string format?


  • Subject: Re: How to transform a NSString to a NSString C string format?
  • From: "Stephen J. Butler" <email@hidden>
  • Date: Thu, 5 Feb 2009 19:46:20 -0600

On Thu, Feb 5, 2009 at 4:52 PM, Iceberg-Dev <email@hidden> 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 ], "\\xx", 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 (email@hidden)

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:

This email sent to email@hidden

References: 
 >How to transform a NSString to a NSString C string format? (From: Iceberg-Dev <email@hidden>)

  • Prev by Date: Re: How to transform a NSString to a NSString C string format?
  • Next by Date: Re: Needed : set class for Cocoa
  • Previous by thread: Re: How to transform a NSString to a NSString C string format?
  • Next by thread: underlining
  • Index(es):
    • Date
    • Thread