user4766244
user4766244

Reputation: 69

Concatenate Strings in C

My assignment is to concatenate v1 onto v2 and the function my_strcat() has to be void. How can I use a void function to return the concatenated strings?

int main(void){
    char v1[16], v2[16];
    int i1, i2;
    printf("Enter First Name: \n");
    scanf("%s", v1);
    printf("Enter Last Name: \n");
    scanf("%s", v2);
    i1 = my_strlen(v1);
    i2 = my_strlen(v2);
    printf("len: %3d - string: %s \n", i1, v1);
    printf("len: %3d - string: %s \n", i2, v2);
    my_strcat(v1, v2);
    printf("Concatenated String: %s \n", v1);
    return 0;
}

void my_strcat (char s1[], char s2[]){
    int result[16];
    int i = 0;
    int j = 0;
    while(s1[i] != '\0'){
        ++i;
        result[i]= s1[i];
    }
    while(s2[j] != '\0'){
        ++j;
        result[i+j] = s2[j];
    }
    result[i+j] = '\0';
}

Upvotes: 1

Views: 121

Answers (1)

avinash pandey
avinash pandey

Reputation: 1381

void my_strcat (char s1[], char s2[],char result[]){
    int result[16];
    int i = 0;
    int j = 0;
    while(s1[i] != '\0'){
        result[i]= s1[i];
        ++i;
    }
    while(s2[j] != '\0'){
        result[i+j] = s2[j];
        ++j;
    }
    result[i+j] = '\0';
}

You can do something like this..I main() declare a third result string whose size is size(v1)+size(v2)+1

char result[33];
my_strcat(v1,v2,result);

Output:

Enter First Name: avinash
Enter Last Name: pandey
len:   7 - string: avinash 
len:   6 - string: pandey 
Concatenated String: avinashpandey 

Upvotes: 1

Related Questions