So if I input: "Ben" and "Tom", the returned string would be "BTeonm". I gotta do it without using prebuilt functions. I've got absolutely no idea how to approach this one, because I'm pretty new to C.
Any hint or help would be really appreciated!
So if I input: "Ben" and "Tom", the returned string would be "BTeonm". I gotta do it without using prebuilt functions. I've got absolutely no idea how to approach this one, because I'm pretty new to C.
Any hint or help would be really appreciated!
Because is a summer saturday and I'm happy, I've written a little code for you, but it's incomplete.
The only "prebuilt" function that the code uses is puts
and I don't see way to don't use it.
The code has two problems:
The strings cannot be longer than 64 bytes. If they are longer the result will be cutted.
The strings should be of equal length. If are of different length the result will be cutted to the length of the shorter string.
Now you shall solve the two problems ... I hope you do this!
You may run the code from the command line as
intesect string1 string2
... and it will give you the reply!
Here the code:
#include <stdio.h>
char * intersect(char *c, int clen, const char *a, const char *b);
int main(int argc, char *argv[])
{
char c[129];
if (argc<3) {
puts("Usage: intersect stringA stringB\n");
return 1;
}
puts(intersect(c,sizeof(c),argv[1],argv[2]));
return 0;
}
char * intersect(char *c, int clen, const char *a, const char *b)
{
int i=0,j=0;
while (a[i] && b[i] && j<clen-2){
c[j++]=a[i];
c[j++]=b[i++];
}
c[j]=0;
return c;
}
Here is another way to approach it, without any string-length limitations:
char *strmix(const char *str1,const char *str2);
int main(int argc, char *argv[])
{
char *p;
if (argc<3) {
puts("Usage: blend stringA stringB\n");
return 1;
}
puts(p = strmix(argv[1],argv[2]));
free(p);
return 0;
}
char *strmix(const char *str1,const char *str2)
{
char *str = malloc(strlen(str1) + strlen(str2) + 1);
char *p = str;
while (*str1 || *str2) {
if (*str1)
*p++ = *str1++;
if (*str2)
*p++ = *str2++;
}
*p = 0;
return str;
}
If you are not allowed to use strlen
, you should be able to create your own fairly easily.