How to concatenate two strings with many null characters?

How to concatenate two strings for example

char s[5]={'s','a','\0','c','h'};

char m[11]={'b','e','\0','c','h','b','\0','e','\0','c','h'};

that has many null characters. I tried strcat(). Its not working. Is there any way?

Answers


This is tricky, because by definition C-strings are null-terminated. So what you really have are two byte buffers that you want to put together, not two strings. (This is why functions like strcat don't work here, by the way -- they expect their arguments to be C-strings.)

Since you can't use the null character to tell you where the buffer ends as you can with C-strings, you need to know the size of the buffers in advance. Then it's as simple as bit-blitting the two into a single buffer:

char dest[16];
memcpy(dest,     s, 5);  // Copy s to the final buffer
memcpy(dest + 5, m, 11); // Copy m to the final buffer just after s

The more straightforward way:

const int size_s = 5;
const int size_m = 11;
char s[size_s]={'s','a','\0','c','h'};
char m[size_m]={'b','e','\0','c','h','b','\0','e','\0','c','h'};
char destination[size_s+size_m];
int i;
for (i = 0;i < size_s;i++)
    destination[i] = s[i];

for (i = 0;i < size_m;i++)
    destination[i+size_s] = m[i];

Ideally, you should use memcpy

const int size_s = 5;
const int size_m = 11;
char s[size_s]={'s','a','\0','c','h'};
char m[size_m]={'b','e','\0','c','h','b','\0','e','\0','c','h'};
char destination[size_s+size_m];

memcpy(destination,s,size_s);
memcpy(destination,m,size_m);

char s[5]={'s','a','\0','c','h'};
char m[11]={'b','e','\0','c','h','b','\0','e','\0','c','h'};
char* e = (char*)malloc(sizeof(s) + sizeof(m));

memcpy(e, s, sizeof(s));
memcpy(&e[sizeof(s)], m, sizeof(m));

don't forget to delete the result string when you are done.

free(e);

All the C standard library string functions will stop on the first \0. That's by design. In fact your input arrays will not work well with such functions since they don't end with a \0.

So the easiest thing for you to do is to use memcpy instead, and specify the number of characters to copy yourself. Don't forget to allocate the necessary amount of memory in the destination buffer.


Need Your Help

Whats wrong in my onStart code?

android android-studio onstart

EDIT: I have found the problem and it is the Thread.Sleep is there any other way of making my application wait a second?

How can I avoid sprite distortion as the frame's bounding box changes?

libgdx sprite bounding-box distortion

I have a spritesheet (packed by the wonderful TexturePacker) that looks like so: