1
0
Fork 0
This repository has been archived on 2021-11-03. You can view files and clone it, but cannot push or open issues or pull requests.
uni-m.cds-adv-prog/ex1/ex1.3/join_strings.cpp

54 lines
1.2 KiB
C++

#include <iostream>
#include <string.h>
// join will return a pointer of type 'char'
char* join(const char*, const char*) ;
char* joinb(const char*, const char*) ;
int main()
{
std::cout << join("alpha","bet") << std::endl ;
std::cout << joinb("duck","soup") << std::endl ;
return 0 ;
}
/* this function is owner of new_str,
* since it doesn't delete it, there is leakage
*/
char* join(const char* str1 , const char* str2)
{
/* use 'new' because we don't know how big the strings are going to be
* the length should be 'strlen(str1) + strlen(str2) + 1'
* since strlen does not count the null bytes we need to add one
*/
int size = strlen(str1) + strlen(str2) + 1;
char* new_str = new char[size];
*new_str = 0; // Null String
strcat(new_str, str1); // new_str = 0 + str1
strcat(new_str, str2); // new_str = new_str + str2
return new_str;
}
char* joinb(const char* str1 , const char* str2)
{
int size = strlen(str1) + strlen(str2) + 1;
char* new_str = new char[size];
*new_str = 0;
strcat(new_str, str1);
strcat(new_str, " "); // insert space, note it is important to have it as a string => \"
strcat(new_str, str2);
return new_str;
}