Reputation: 9541
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
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
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
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