SycoSins
SycoSins

Reputation: 39

Append part of a string to another string

I'm trying to make a simple program where parts of other strings are appended to another string. When I run this code, it doesn't output anything. Sorry, my C knowledge is very low. All help appreciated.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char stuff[100] = "Y";
    char test[] = "hello", test2[] = "shelllo";

    strcat(stuff, test[1]);
    strcat(stuff, test2[0]);

    printf("%s\n", stuff);

    return 0;
}

Upvotes: 2

Views: 3518

Answers (2)

chqrlie
chqrlie

Reputation: 144951

You are calling strcat with a char argument instead of a pointer to char, the behavior is undefined.

Here are solutions to copy portions of strings:

  • using strncat(): it copies no more than a given number of characters to the end of its first argument.
  • using snprintf() with the %.*s format. The precision field for the %s format specifies the maximum number of characters to copy from the string. It can be specified as a decimal number or as a * in which case the precision is passed as an int argument before the string argument.

Here is an example:

#include <stdio.h>
#include <string.h>

int main(void) {
    char stuff[100];
    char test[] = "Hello";
    char test2[] = "The world is flat";

    /* using strncat */
    strcpy(stuff, test);
    strncat(stuff, test2 + 3, 6);
    printf("%s\n", stuff);

    /* safer version using snprintf */
    snprintf(stuff, sizeof stuff, "Hello %.*s\n", 5, test2 + 4);
    printf("%s\n", stuff);

    return 0;
}

Upvotes: 2

tdao
tdao

Reputation: 17678

You need to remove array index from your strcat which should look like:

strcat(stuff, test);
strcat(stuff, test2);

Note that test and test2 are strings, but test[1] and test2[0] are just individual characters (e and s) - strcat works with string, not individual characters.

If you want to copy just part of a string (ie skipping first few characters), then use pointer arithmetic

strcat(stuff, test + 1); // skip 1st character of test (ie start copying from `e`)

or,

strcat(stuff, test2 + 3); // skip 3 characters of test2 (ie starting copying from `l`)

Upvotes: 2

Related Questions