/*
  CGS 3460 Computer Programming Using C
  Homework 6
  Problem 1
  Author: Cem Boyaci
  
  For questions send email to: cboyaci@cise.ufl.edu

*/

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


// Appends first n character of str2 to the end of str1
char* concat_n(char* str1, char* str2, int n){

  // obtain string lengths
  int len_str1 = strlen(str1);
  int len_str2 = strlen(str2);
  

  // if n is larger than str2's length
  if(n<len_str2){
    len_str2 = n;
  }
  
  // total length
  int total     = len_str1 + len_str2;
  // allocate memory
  // one extra space is for string termination character
  char* result  = (char*)malloc(((total*sizeof(char))+1)); 
 
  // pointer operations
  int i;

  // copy str1 to result
  for(i=0;i<len_str1;i++){
    *(result+i) = *(str1+i);
  }
  
  // append n characters to the end
  for(i=0;i<len_str2;i++){
    *(result+len_str1+i) = *(str2+i);
  } 
  
  *(result+len_str1+len_str2) = '\0';  
  
  
  // This is how memcpy would have handled this task
  // This is ussually preferred, where they are very similar in nature 
  /*
  memcpy(result,str1,len_str1);
  memcpy(result+len_str1,str2,len_str2);
  memcpy(result+len_str1+len_str2,"\0",1);
  */

  return result;
}


int main(){
  
  char str1[100];
  char str2[100];
  int n;  

  printf("Please enter the first string\n");
  scanf("%s",str1);
  printf("Please enter the second string\n");
  scanf("%s",str2);
  printf("Please enter the number of characters from the second string to append\n");
  scanf("%d",&n);

  printf("Appended string is: \n");
  printf("%s\n",concat_n(str1,str2,n)); 

  return 0;

} 

