Add 2 strings in C
×


Add 2 strings in C

200

 Adding two strings in C involves concatenating them, which means joining the contents of one string to the end of another.

 String concatenation is a fundamental operation in string manipulation, extensively used in programming for tasks like building messages, combining text, or constructing file paths.

 step-by-step explanation of how to add two strings in C:

 Declare the Strings: First, declare two character arrays to hold the strings you want to concatenate.

 Ensure that the arrays are large enough to accommodate the combined length of both strings and a null terminator.

char string1[50] = "Hello", ;
char string2[] = "programming";

 In this example, string1 is initialized with "Hello".

 Use Concatenation Function: Utilize a string concatenation function to append the content of the second string to the end of the first one.

 In C, the strcat() function from the library is commonly used for this purpose.

strcat(string1, string2);

 This statement concatenates string2 to the end of string1.

 Please display the Result: Finally, print or use the concatenated string as needed.

printf("Concatenated string: %s\n", string1);

 This will display the concatenated string.

 "Hello", "programming".

Example:

// program for two strings in C
#include<stdio.h> 
#include<string.h> 

int main() {
    char string1[50] = Hello, ;
    char string2[] = programming;
    
    // Concatenating string2 to string1
    strcat(string1, string2);
    
    printf("Concatenated string: %s\n", string1);
    
    return 0;
}	

Output:

Concatenated string: Hello, programming 


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments