55

I have a variable of type char[] and I want to copy NSString value in it. How can I convert an NSString to a char array?

JAL
  • 41,701
  • 23
  • 172
  • 300
sagar
  • 571
  • 1
  • 5
  • 4

6 Answers6

107

Use -[NSString UTF8String]:

NSString *s = @"Some string";
const char *c = [s UTF8String];

You could also use -[NSString cStringUsingEncoding:] if your string is encoded with something other than UTF-8.


Once you have the const char *, you can work with it similarly to an array of chars:

printf("%c\n", c[5]);

If you want to modify the string, make a copy:

char *cpy = calloc([s length]+1, 1);
strncpy(cpy, c, [s length]);
// Do stuff with cpy
free(cpy);
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • 7
    He asked for a char array this is a const char – JonasG Mar 21 '12 at 14:39
  • Im looking for a complete answer that shows the code from `NSString *someString` to `char myArray[] =..`. I really need this, could you please update your answer? cheers – JonasG Mar 21 '12 at 17:40
  • @Maxner: What do you need to do? In most cases, a pointer to chars can be used like a char array. – mipadi Mar 21 '12 at 17:52
  • I need a char array like this one `char csignid[] = "something";` but with the `something`from an NSString. I need it to be able to modify the array like this `csignid[5] = a+0x21;`. Declaring the char array like this `char csignid[] = [@"dunno" UTF8String];` or `const char* csignid[] = [@"" UTF8String];`returns an error message saying 'Array initializer must be an initializer list'. Thanks – JonasG Mar 21 '12 at 17:58
  • I would suggest the following one-liner to get a cstring copy strdup([s UTF8String]); – pronebird Feb 13 '13 at 13:37
14

mipadi's answer is the best if you just want a char* containing the contents of the string, however NSString provides methods for obtaining the data into a buffer that you have allocated yourself. For example, you can copy the characters into an array of unichar using getCharacters:range: like this:

NSUInteger length = [str length];
unichar buffer[length];

[str getCharacters:buffer range:NSMakeRange(0, length)];

for (NSUInteger i = 0; i < length; i++)
{
    doSomethingWithThis(buffer[i]);
}

If you have to use char, then you can use the more complicated getBytes:maxLength:usedLength:encoding:options:range:remainingRange: like this (demonstrated in Eastern Polish Christmas Tree notation):

NSUInteger length = [str length];
NSUInteger bufferSize = 500;

char buffer[bufferSize] = {0};

[str       getBytes:buffer
          maxLength:(bufferSize - 1)
         usedLength:NULL
           encoding:NSUTF8StringEncoding
            options:0
              range:NSMakeRange(0, length)
     remainingRange:NULL];
dreamlax
  • 93,976
  • 29
  • 161
  • 209
10
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < [string length]; i++) {
    [array addObject:[NSString stringWithFormat:@"%C", [string characterAtIndex:i]]];
}
adjwilli
  • 9,658
  • 4
  • 35
  • 29
3

Rather than getCharacters:range:, I use:

[stringToCopy getCString:c_buffer maxLength:c_buffer_length encoding:NSUTF8StringEncoding];

The result is a char[] (instead of unichar[]), which is what the OP was wanting, and what you probably want to use for C compatibility.

DefenestrationDay
  • 3,712
  • 2
  • 33
  • 61
0

In Swift, a char array is bridged as an UnsafePointer<Int8>. Accessing characters works the same way in Swift for an NSString:

let str: NSString = "hello"
let charStr = str.UTF8String // UnsafePointer<Int8>

For a Swift String object things are a little different:

let str = "hello"
let charStr = str.cStringUsingEncoding(NSUTF8StringEncoding)

charStr is [CChar]? where CChar is a typeailais for Int8.

JAL
  • 41,701
  • 23
  • 172
  • 300
0

We need to play NSString as a character array for working on coding practices which is otherwise much simpler to do in plain C coding. Using characterAtIndex: and appendFormat: helps me. May be this will help.

NSString *str = @"abcdef";
NSMutableString *strResult = [NSMutableString string];

for (NSUInteger i = 0; i < [str length]; i++) {
  char ch = [str characterAtIndex:i];
  [strResult appendFormat:@"%c", ch];
}
NSLog(@"%@", strResult);
Debaprio B
  • 503
  • 7
  • 9
  • 1
    whats the diff between your answer and.... NSMutableString *strResult = [NSMutableString stringWithString:str]; ? – greenhouse Feb 13 '18 at 07:10