name_masked
name_masked

Reputation: 9793

Split a string and combine 2 strings - C

I am trying to do a split of a string and then insert another string into the 1st string at the point of split.

Example:

int main(int argc, char **argv)
{
    char src1[4]= "foo";
    char src2[4]= "bar";

}

I would like to split the src1 as f and oo to insert src2, so that I get a single string fbaroo. What is the best way to do it in C?

I tried using snprintf, but I am not able to achieve the same. Following is the code:

snprintf(result, 1,"%s",src1[0]);
snprintf(result, strlen(src2), "%s",src2);
snprintf(result, strlen(src1)-1, "%s", **how do i get remaining characters**);

Ofcourse, I can have it initially split to combine later, but I am trying to find if there is a better solution i.e. using library functions ?

Upvotes: 1

Views: 199

Answers (3)

Rubens
Rubens

Reputation: 14778

I'd go with sprintf():

# include <stdio.h>

int main(int argc, char **argv) {

    char src1[4] = "foo";
    char src2[4] = "bar";
    char result[8] = {'\0'};

    sprintf(result, "%c%s%s", src1[0], src2, &src1[1]);
    printf("Result: [%s];\n", result);

}

Output:

$ ./a.out 
Result: [fbaroo];

Upvotes: 1

Manuel Miranda
Manuel Miranda

Reputation: 823

First you need a new string with enought space:

char finalString[7];

Then you need to copy the X first chars from src1 to our new string, you can achieve this by memcpy, or stcpy, I'll go with the later. So if you only want to copy the first character from src1you should do:

strcpy(finalString, src1, 1);

now just copy the src2 string onto it using strcat

strcat(finalString, src2);

and append the rest of the src1 string, starting in the first uncopied char:

strcat(finalString, &src1[1]);

Upvotes: 1

Doug Currie
Doug Currie

Reputation: 41200

The snprintfs in your code all all overwriting the buffer from the start.

Here's one way to do it with one call

snprintf(result, sizeof(result), "%c%s%s", src1[0], src2, &src1[1]);

The &src1[1] shows how to get "the rest of the string."

Upvotes: 1

Related Questions