concatenate two strings without standard library in C
To concatenate two strings without using the standard library in C, you can follow these steps:
Step 1: Declare two character arrays to store the strings you want to concatenate. Let's assume the first string is str1
and the second string is str2
.
Step 2: Find the length of str1
and str2
using a loop that iterates until the null character ('\0'
) is encountered. This will help determine the length of the strings.
Step 3: Create a new character array to store the concatenated string. The size of this array should be equal to the sum of the lengths of str1
and str2
plus one extra character for the null character.
Step 4: Copy the characters from str1
to the new concatenated string array using a loop that iterates until the null character is encountered.
Step 5: Append the characters from str2
to the concatenated string array using another loop. Start from the position where str1
ends and iterate until the null character is encountered.
Step 6: Add a null character ('\0'
) at the end of the concatenated string array to mark the end of the concatenated string.
Here is an example code snippet that demonstrates the above steps:
#include <stdio.h>
void concatenateStrings(char str1, char str2, char* result) {
int i, j;
// Step 2
for (i = 0; str1[i] != '\0'; i++) {
result[i] = str1[i];
}
// Step 5
for (j = 0; str2[j] != '\0'; j++) {
result[i + j] = str2[j];
}
// Step 6
result[i + j] = '\0';
}
int main() {
char str1[] = "Hello";
char str2[] = " World";
char result[12]; // Size should be equal to the length of str1 + str2 + 1
// Step 1
concatenateStrings(str1, str2, result);
printf("Concatenated string: %s\n", result);
return 0;
}
In this example, the concatenateStrings
function takes three arguments: str1
, str2
, and result
. It performs the concatenation and stores the result in the result
array.
The main
function declares str1
, str2
, and result
arrays. It then calls the concatenateStrings
function to concatenate str1
and str2
and stores the result in the result
array. Finally, it prints the concatenated string.
The output of the above code will be:
Concatenated string: Hello World
By following these steps, you can concatenate two strings without using the standard library in C.