Cover Image for Add String in C

Add String in C

The concatenate (add) strings using the strcat function from the standard library <string.h>. However, C doesn’t have built-in support for manipulating strings as easily as some other languages like C++ or Python. Here’s a simple example of how to concatenate strings in C:

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

int main() {
    char str1[100]; // Declare the first string
    char str2[100]; // Declare the second string

    // Input the first string
    printf("Enter the first string: ");
    scanf("%s", str1);

    // Input the second string
    printf("Enter the second string: ");
    scanf("%s", str2);

    // Concatenate str2 to str1
    strcat(str1, str2);

    // Print the concatenated string
    printf("Concatenated string: %s\n", str1);

    return 0;

In this program:

  1. We declare two character arrays str1 and str2, which will store the input strings.
  2. We use scanf to input the first and second strings from the user. Note that scanf reads only one word at a time, separated by spaces.
  3. We use the strcat function to concatenate str2 to the end of str1. The strcat function modifies str1 in place and appends the characters of str2 to it.
  4. Finally, we print the concatenated string.

Keep in mind that this example assumes that the input strings do not exceed the array size (100 in this case), and it doesn’t handle cases where the result of concatenation may exceed the available space in str1. In real-world scenarios, you should perform proper error checking and allocate memory dynamically as needed.

Additionally, C also provides a safer alternative to strcat called strncat, which allows you to specify the maximum number of characters to concatenate to avoid buffer overflows.


The Tech Thunder

The Tech Thunder

The Tech Thunder