开发者_高级运维Possible Duplicate:
C String Concatenation
How do I concatenate multiple char strings in C ?
Example:
const char *bytes = "tablr=Hello%20World";
const char *bytes2 = "tablr=Hello%20World";
const char *bytes3 = "tablr=Hello%20World";
thanks
Here's a suggestion, that avoids the Painter's problem:
char const *bytes = "tablr=Hello%20World";
char const *bytes2 = "tablr=Hello%20World";
char const *bytes3 = "tablr=Hello%20World";
unsigned int const sz1 = strlen(bytes );
unsigned int const sz2 = strlen(bytes2);
unsigned int const sz3 = strlen(bytes3);
char *concat = (char*)malloc(sz1+sz2+sz3+1);
memcpy( concat , bytes , sz1 );
memcpy( concat+sz1 , bytes2 , sz2 );
memcpy( concat+sz1+sz2 , bytes3 , sz3 );
concat[sz1+sz2+sz3] = '\0';
/* don't forget to free(concat) when it's not needed anymore */
This avoids the painter's problem and should be more efficient (although sometimes not) because memcpy may copy byte-by-byte or word-by-word, depending on the implementation, which is faster.
If you can see a pattern here, this can easilly be transformed into a function that concatenates an arbitrary number of strings, if they are provided in an char const*[]
String literals can be concatenated simply by being adjacent:
const char *whole_string = "tablr=Hello%20World" "tablr=Hello%20World" "tablr=Hello%20World";
The above concatenation is done by the compiler and doesn't incur runtime overhead.
In general, you use the strcat
function declared in <string.h>
.
But you can concatenate string literals merely by writing them one after another. Example:
const char *p = "Hello, " "World"
"!";
p points to "Hello, World!".
In your case it would be like this:
const char* p =
"tablr=Hello%20World"
"tablr=Hello%20World"
"tablr=Hello%20World";
With string.h
included (the easy but "slow" (not really very slow ;P) way):
char * result = calloc(strlen(bytes)+strlen(bytes2)+strlen(bytes3)+1,sizeof(char));
strcat(result, bytes);
strcat(result, bytes2);
strcat(result, bytes3);
Using an efficient loop:
int i, j, len = strlen(bytes)+strlen(bytes2)+strlen(bytes3)+1;
char * result = malloc(sizeof(char)*len);
for(i = 0; i < len && bytes[i] != '\0'; i++)
result[i] = bytes[i];
for(j = 0; i < len && bytes2[j] != '\0'; i++, j++)
result[i] = bytes2[j];
for(j = 0; i < len && bytes3[j] != '\0'; i++, j++)
result[i] = bytes3[j];
result[i] = '\0';
Use the strcat
or strncat
functions. Be careful with the memory allocations around those though.
If your compiler supports it use strcat_s or _tcscat_s. They will check the buffer length you're writing to.
I suggest to use memcpy function. It is quite efficient:
int l1 = strlen(bytes), l2 = strlen(bytes2), l3 = strlen(bytes3);
int length = l1+l2+l3;
char *concatenatedBytes = (char *)malloc((length+1)*sizeof(char));
memcpy(concatenatedBytes, bytes, l1);
memcpy(concatenatedBytes + l1, bytes2, l2);
memcpy(concatenatedBytes + l1 + l2, bytes3, l3);
concatenatedBytes[length] = 0;
精彩评论