Add string in C
×


Add string in C

261

 Adding strings in C involves concatenating one string to another.

 Strings in C are represented as arrays of characters, terminated null character '\0'

 To add a string, you need to find the end of the first string and append characters from the second string until you encounter the null character.

Here's a basic approach:

 Find the length of the first string.

 Iterate through the second string and append each character to the end of the first string.

 Add a null character at the end of the concatenated string to terminate it properly.

Here's a simple C program demonstrating how to add strings:

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

int main() {
    char str1[50] = "Hello, ";
    char str2[] = "world!";
    
    // Find the length of the first string
    int len1 = strlen(str1);
    
    // Concatenate the second string to the end of the first string
    int i;
    for (i = 0; str2[i] != '\0'; i++) {
        str1[len1 + i] = str2[i];
    }
    str1[len1 + i] = '\0'; // Add null character
    
    printf("Concatenated string: %s\n", str1);
    
    return 0;
}

Output:

Concatenated string: Hello, world!

 This program first initializes two strings str1 and str2.

 Then, it finds the length of str1 using the strlen function from the library.

 Next, it iterates through str2, appending each character to the end of str1.

 Finally, it adds a null character at the end of the concatenated string and prints the result.

 You can modify this program according to your specific requirements, such as dynamically allocating memory for the strings or using library functions like strcat for concatenation.



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