strings concatenation in C
×


strings concatenation in C

202

 Concatenation of strings in C refers to the process of combining or joining two or more strings together to form a single string.

 In C, strings are represented as arrays of characters terminated by a null ('\0') character.

There are multiple ways to concatenate strings in C, both using standard library functions and manual methods.

Using Standard Library Functions

1strcat() Function:

The strcat() function is used to concatenate two strings. It appends the content of the source string to the destination string.

Syntax:

char* strcat(char* destination, const char* source);

Example:

#include<stdio.h>
#include<string.h>

int main() {
    char str1[50] = "Hello";
    char str2[] = " World";

    strcat(str1, str2);

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

    return 0;
}
	

Output:

Concatenated string: Hello World
2Using sprintf() Function:

The sprintf() function can be used to format and store a series of characters in a string buffer.

Syntax:

int sprintf(char* buffer, const char* format, ...);

Example:

#include<stdio.h>

int main() {
    char buffer[50];
    char str1[] = "Hello";
    char str2[] = " World";

    sprintf(buffer, "%s%s", str1, str2);

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

    return 0;
}

Output:

Concatenated string: Hello World

Manual Concatenation

Using Loops:

You can use loops like for or while to manually concatenate strings character by character.

Example:

#include<stdio.h>

int main() {
    char str1[50] = "Hello";
    char str2[] = " World";
    int i, j;

    for (i = 0; str1[i] != '\0'; ++i);

    for (j = 0; str2[j] != '\0'; ++j, ++i) {
        str1[i] = str2[j];
    }

    str1[i] = '\0';

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

    return 0;
}

Output:

Concatenated string: Hello World

Key Points:

Null Termination: Ensure that the destination string has enough space to accommodate the concatenated result and ends with a null character ('\0').

Buffer Overflow: Be cautious about buffer overflows while concatenating strings manually to avoid undefined behavior.



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