How do I "include" a string into another string in C ?
Here is an example :
string1 = "www.google";
string2 = "http://"+string1+".com";
I'm having difficulties with strcat().
Thanks
How do I "include" a string into another string in C ?
Here is an example :
string1 = "www.google";
string2 = "http://"+string1+".com";
I'm having difficulties with strcat().
Thanks
You can use snprintf
and its feature to return the size it would need if it had the space available:
const char *string1 = "www.google";
char *string2;
size_t length;
length = snprintf(NULL, 0, "http://%s.com", string1);
if (length < 0) {
// Handle error.
} else {
string2 = malloc(length + 1);
snprintf(string2, length + 1, "http://%s.com", string1);
}
Slightly different variant which avoids having the format string two times:
const char *string1 = "www.google";
const char *format = "http://%s.com";
char *string2;
size_t length;
length = snprintf(NULL, 0, format, string1);
if (length < 0) {
// Handle error.
} else {
string2 = malloc(length + 1);
snprintf(string2, length + 1, format, string1);
}
I'm having difficulties with strcat()
Then try sprintf:
char str[] = "www.google";
char dest[100];
snprintf(dest, sizeof(dest), "http://%s.com", str);
7.19.6.5-3
The
snprintf
function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character.