strcat without using built in function
Certainly! Here is an example of how to implement the strcat
function in C++ without using the built-in function:
#include <iostream>
void strcat_custom(char destination, const char source) {
// Find the end of the destination string
while (*destination) {
destination++;
}
// Copy the characters from the source string to the end of the destination string
while (*source) {
destination = source;
destination++;
source++;
}
// Add the null terminator to the end of the concatenated string
*destination = '\0';
}
int main() {
char str1[20] = "Hello";
const char* str2 = " World!";
strcat_custom(str1, str2);
std::cout << str1 << std::endl;
return 0;
}
Explanation:
- The
strcat_custom
function takes two parameters:destination
(the string to append to) andsource
(the string to append). - We start by finding the end of the
destination
string. This is done by iterating through the characters of the string until we reach the null terminator ('\0'
). - Once we have reached the end of the
destination
string, we start copying the characters from thesource
string to the end of thedestination
string. This is done by iterating through the characters of thesource
string and copying each character to thedestination
string. - After copying all the characters from the
source
string to thedestination
string, we add the null terminator ('\0'
) to the end of the concatenated string to ensure it is properly terminated. - In the
main
function, we demonstrate the usage of thestrcat_custom
function by concatenating the strings "Hello" and " World!". The result is stored in thestr1
array, and then printed to the console usingstd::cout
.
This implementation of strcat
without using the built-in function showcases how you can manually concatenate two strings by iterating through the characters and copying them to the destination string.