-4

I need to build a function in C, that receives two strings str1 and str2 and returns a string that is the concatenation str1 and str2, but I need to discard the last elements of str1 that are equal to the first elements of str2.

Example 1:

str1 = ccabcc
str2 = ccbabd
result : ccabccbabd

Example 2:

str1 = abbcbf
str2 = ab
Result : abbcbfab

Sometimes there is no overlapping.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
cacc
  • 35
  • 5
  • 3
    Everyone here will help you, But you should help yourself first. Try some code yourself, and ask questions here if you face some difficulty. – Haris Jul 28 '15 at 13:41
  • 1
    Hint: check for str1[last] equals the str2[first] in a loop decrementing last index and incrementing first index until they are not equal. The moment when they are not equal, append str2[first] to str1[strlen[str1]]. – Sunil Bojanapally Jul 28 '15 at 13:48
  • @SunilBojanapally: What you're proposing is an inverted palindrome check, but that doesn't fit example 1. – EOF Jul 28 '15 at 14:00
  • Thank you @haris and @SunilBojanapall! Done! – cacc Jul 28 '15 at 15:04
  • @EOF When the loop terminates, index `first` will be pointing to char literal in str2 which is not matching with str1 from last. – Sunil Bojanapally Jul 29 '15 at 07:50

3 Answers3

0

This problem is trivial imho. Personally, I would go with something like this(it is pseudo code):

function(str1,str2)
int j = 0
int lstr1 = lenght of str 1
int lstr2 = lenght of str 2
while(true)  
  if(str1[lstr1 - j] == str2[j])
    j++ 
 else
   break
 return str1 + str2[j to end of string]

If I did not make logic mistake, you code should look like something that compare the end of str 1 to beginning of str 2 and increment. Also, my pseudo code don't take into account the string lenght and potential overflow error.

MathieuL
  • 155
  • 7
0

I hope this is what you need:

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

char *concate(char *first, char *second){
    size_t len1 = strlen(first);
    size_t len2 = strlen(second);
    char *res = (char *)malloc(len1 +len2 +1);

    if(res==NULL){
        exit(1);
    }

    if(first[len1-1] == second[0]){
        first[len1-1] = 0;
        second++;
    }

    strcpy(res,first);
    strcat(res,second);

    return res;
}

int main(void){
    int i = 0,len = 0;
    char arr[] = "ccabcc";
    char arr2[] = "ccbabd";
    char *res = concate(arr,arr2);

    while(res[len] != '\0'){
        len++;
    }

    for(i=0;i<len;i++){
        printf("%c",res[i]);
    }

    printf("\n");
    free(res);
    return 0;

}

Output:

ccabccbabd

Michi
  • 5,175
  • 7
  • 33
  • 58
-4
int main(){
    char a[256], b[256];

    printf("Enter 1st string\n");
    gets(a);


    printf("Enter the 2nd string\n");
    gets(b);

    strcat(a,b);
    printf("String concatenation is %s\n",a);

}
eboix
  • 5,113
  • 1
  • 27
  • 38
Regan
  • 21
  • 2