The Program in C to concatenate 2 strings using pointers without strcat function is given below:
#include <stdio.h>
void concatenateStrings(char *s1, char *s2) {
while (*s1 != '\0') {
s1++;
}
while (*s2 != '\0') {
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
}
int main() {
char str1[100], str2[100];
printf("Enter the first string: ");
scanf("%s", str1);
printf("Enter the second string: ");
scanf("%s", str2);
concatenateStrings(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
Output:
Enter the first string: hello
Enter the second string: codeauri
Concatenated string: hellocodeauri
Pro-Tips💡
This program uses a while loop to iterate through the first string, it uses pointers to traverse the string until it reaches the null character ‘\0’ which indicates the end of the string.
Then it starts iterating through the second string, it uses the same pointer to traverse the second string,
and at each iteration assigns the value of the current character of the second string to the current position of the first string and increments the pointer of the first string,
once it reaches the end of the second string it assigns the null character ‘\0’ to the current position of the first string to indicate that the concatenation is finished.
This program doesn’t use the strcat function, instead it uses pointers to traverse the strings and concatenate them.
Please note that the program uses scanf(“%s”,…) to read the input strings, which does not include spaces, if you want to include spaces, you should use fgets() or gets() (not recommended).
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.