开发者

char *cQuery append string

I have a String and I declared it a开发者_C百科s

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


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);


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");


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);
}


Use strcat see help here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜