2

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

Kevin
  • 53,822
  • 15
  • 101
  • 132
kyori
  • 487
  • 1
  • 7
  • 21

2 Answers2

5

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);
}
DarkDust
  • 90,870
  • 19
  • 190
  • 224
4

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.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • 3
    And be aware that this results in a potential buffer overflow if you don't check the length of `str` first! – Thomas Feb 04 '12 at 20:08
  • `snprintf` can tell you how much space it would need, which makes it easy to allocate exactly the amount of memory needed instead of using a static buffer. – DarkDust Feb 04 '12 at 20:11
  • @DarkDust That's right, you just have to pass it 0 as the size. – cnicutar Feb 04 '12 at 20:11
  • @DarkDust [The Microsoft C Runtime Library version of snprintf](http://msdn.microsoft.com/en-us/library/2ts7cx93(v=vs.80).aspx) doesn't return the required buffer size, but returns -1 to signal failure (ditto for very old versions of glibc), so sadly it's not portable. – GameZelda Feb 04 '12 at 21:16
  • @GameZelda That's unfortunate but good to know. I edited the question to make it completely clear that the "could have written" behavior is required by the standard. – cnicutar Feb 04 '12 at 21:19
  • @GameZelda: Well, the behavior I cited is required by C99 §7.19.6.5(3). I guess this is why MS named their version `_snprintf` instead. – DarkDust Feb 05 '12 at 16:38