Write a C program to concatenate two strings using pointers.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char str1[256], str2[256], *res;
int i, j, len;
/* get the first input string from the user */
printf("Enter your first input string:");
fgets(str1, 256, stdin);
str1[strlen(str1) - 1] = '\0';
/* get the secon input string from the user */
printf("Enter your second input string:");
fgets(str2, 256, stdin);
str2[strlen(str2) - 1] = '\0';
/*
* length of concatenated string is equal
* to the sum of lengths of given input strings
*/
len = strlen(str1) + strlen(str2);
/* dynamically allocate memory for output string */
res = (char *) malloc(sizeof(char) * len);
/* concatenates input strings and stores the output in res */
for (i = 0; i < strlen(str1); i++) {
*(res + i) = *(str1 + i);
}
for (j = 0; j <= strlen(str2); i++, j++) {
*(res + i) = *(str2 + j);
}
#include <string.h>
#include <stdlib.h>
int main() {
char str1[256], str2[256], *res;
int i, j, len;
/* get the first input string from the user */
printf("Enter your first input string:");
fgets(str1, 256, stdin);
str1[strlen(str1) - 1] = '\0';
/* get the secon input string from the user */
printf("Enter your second input string:");
fgets(str2, 256, stdin);
str2[strlen(str2) - 1] = '\0';
/*
* length of concatenated string is equal
* to the sum of lengths of given input strings
*/
len = strlen(str1) + strlen(str2);
/* dynamically allocate memory for output string */
res = (char *) malloc(sizeof(char) * len);
/* concatenates input strings and stores the output in res */
for (i = 0; i < strlen(str1); i++) {
*(res + i) = *(str1 + i);
}
for (j = 0; j <= strlen(str2); i++, j++) {
*(res + i) = *(str2 + j);
}
/* print the result */
printf("Result:\n");
printf("String 1: %s\n", str1);
printf("String 2: %s\n", str2);
printf("Output : %s\n", res);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your first input string:India
Enter your second input string:Today
Result:
String 1: India
String 2: Today
Output : IndiaToday
Enter your first input string:India
Enter your second input string:Today
Result:
String 1: India
String 2: Today
Output : IndiaToday
No comments:
Post a Comment