1. Introduction
String concatenation is the operation of joining two strings end-to-end. In C++, the standard library provides a simple way to concatenate strings using the + operator or the append() function for std::string type. However, understanding how this works at a foundational level can provide deeper insights into string manipulations.
In this post, we'll explore how to concatenate two strings in C++ without using library functions.
2. Program Overview
Our program will:
1. Prompt the user to input two strings.
2. Use a function to concatenate these strings manually.
3. Display the concatenated result.
3. Code Program
#include<iostream>
using namespace std;
// Function to concatenate two strings
char* concatStrings(const char* str1, const char* str2) {
int i = 0, j = 0;
while (str1[i] != '\0') {
i++; // Find length of str1
}
// Allocate memory for concatenated string
char* result = new char[i + strlen(str2) + 1];
i = 0;
// Copy str1 to result
while (str1[i] != '\0') {
result[i] = str1[i];
i++;
}
// Copy str2 to result
while (str2[j] != '\0') {
result[i] = str2[j];
i++;
j++;
}
result[i] = '\0'; // Null-terminate the concatenated string
return result;
}
int main() {
char str1[100], str2[100];
// Input strings
cout << "Enter the first string: ";
cin.getline(str1, 100);
cout << "Enter the second string: ";
cin.getline(str2, 100);
char* concatenated = concatStrings(str1, str2);
cout << "Concatenated string: " << concatenated << endl;
delete[] concatenated; // Free the allocated memory
return 0;
}
Output:
Enter the first string: Hello Enter the second string: World Concatenated string: HelloWorld
4. Step By Step Explanation
1. The program starts by prompting the user to enter two strings.
2. The concatStrings function is then called, which manually concatenates the strings.
- The function first calculates the length of the first string.- Then, memory is allocated to hold the concatenated string.- Both strings are copied into this new memory block one after the other.
3. The concatenated string is then displayed to the user.
4. At the end, we free the dynamically allocated memory to prevent memory leaks.
Comments
Post a Comment
Leave Comment