Cocoa Dev
Cocoa Dev

Reputation: 9541

char *cQuery append string

I have a String and I declared it as

char *cQuery = "My Name Is ";

and I want to append another string. In objective-c, I'd say stringByAppendingString:newString

I'm a little rusty with C being used in Objective-C classes. Can anyone help me out?

Thanks

Upvotes: 2

Views: 777

Answers (4)

Sonny Saluja
Sonny Saluja

Reputation: 7287

By declaring the string like so, you are declaring cQuery to be a constant string.

// You can change cQuery using strcat, snprintf etc.
char *cQuery = "My Name Is ";

// Error! Cannot do this.
// strcat(cQuery, "John");

If you want cQuery to be modifiable, you will need to create a char array with an explicit size, then copy over the starting contents into that string.

char cQuery[128];

// use snprintf or strcpy to initialize
strcpy(cQuery, "My name is ");

// now you can modify cQuery by calling strcat.
strcat(cQuery, "Funny Name");

Upvotes: 3

Zan Lynx
Zan Lynx

Reputation: 54325

I would use snprintf. (It's one of my favorite functions!)

Like this:

void add_it(const char *name)
{
    char buffer[256];
    const size_t buffer_len = sizeof(buffer);

    snprintf(buffer, buffer_len, "My Name Is %s", name);
    do_something(buffer);
}

Upvotes: 2

Neil Sainsbury
Neil Sainsbury

Reputation: 1460

You can use the strcat method from string.h but must be mindful that the destination string must be of sufficient size to hold the newly combined strings.

char destination[100];
char *cQuery = "My Name Is ";
char *anotherStr = "Peter";

strcpy(destination, cQuery);
strcat(destination, anotherStr);

Upvotes: 3

theChrisKent
theChrisKent

Reputation: 15099

Use strcat see help here

Upvotes: 1

Related Questions