55 lines
1.3 KiB
C++
55 lines
1.3 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)
|
|
{
|
|
// size should be 2 more than required for the strlens to
|
|
// incorporate the space and the null byte
|
|
int size = strlen(str1) + strlen(str2) + 2;
|
|
|
|
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;
|
|
|
|
}
|