Problem: Write a c program to concatenate two strings and output the final result.
Example:
str1: Hello str2: Universe Output: HelloUniverse str1: Pencil str2: Programmer Output: PencilProgrammer
To concatenate two strings in C, you need to follow the following steps:
- Get two strings as inputs from the user.
- Remove any newline character from the strings.
- Pass the strings to strcat(str1, str2) function as parameters.
This will concatenate str2 at the end of str1.
Let's see the actual implementation of the above algorithm in C:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin); // read the first string from user input
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin); // read the second string from user input
str1[strcspn(str1, "\n")] = 0; // remove the newline character from str1
str2[strcspn(str2, "\n")] = 0; // remove the newline character from str2
strcat(str1, str2); // concatenate str2 onto the end of str1
printf("The concatenated string is: %s\n", str1);
return 0;
}
Output:
Enter the first string: Pencil
Enter the second string: Programmer
The concatenated string is: PencilProgrammer
In the above program, first we ask the user to input two strings and store them into the str1 and str2 variables.
Then, using strcspn(), we check for any newline character in the strings.
If any newline character is present in the string, the strcspn() returns a positive index number. To remove it, we simply assign 0 to that index position in the string.
Finally, using the strcat(str1, str2) function, we append the str2 at the end of the str1.
So, the final value of str1 is the concatenation of two input strings.