Adsense 728 * 15

Search

Custom Search

C Program to Concatenate Two Strings

Write a c program to concatenate two strings. Given two input strings, we have to write a C program to concatenate two strings. 

In this tutorial, we'll take an example of string concatenation using inbuilt string function strcat() as well as without using this inbuilt method.



C Program to Concatenate Two Strings



Logic of concatenating two strings.

i) Declare two character array and take input from user.


ii)  Traverse first string to reach at the end, now start concatenating second string into first.


Programming questions on strings

Let's first take an example of string concatenation using inbuilt function strcat().

C Program to Concatenate Two Strings using strcat


In this example, we take two input strings from user and then concatenate these two strings using strcat() method.


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

int main() {
    
    char str1[100], str2[100];
    
    printf("Enter first string \n");
    fgets(str1, 100, stdin);
    
    printf("Enter second string \n");
    fgets(str2, 100, stdin);
    
    
    //inbuilt library function1
    strcat(str1, str2);
    
    printf("After concatenation %s", str1);
    
    return 0;
}


C Program to Concatenate two Strings without using strcat



In this example, we first traverse a first string and reach at the end of a first string and then start concatenating second string into first string.

#include <stdio.h>

int main() {
    
    char str1[100], str2[100], i = 0, j = 0;
    
    printf("Enter first string \n");
    fgets(str1, 100, stdin);
    
    printf("Enter second string \n");
    fgets(str2, 100, stdin);
    
    
    /* Traverse and 
     *reach at the end of a string
     */
    
    while(str1[i] != '\0') {
        str1[i++];
    }
    
    /*
     * Traverse second string
     * and appends them into first string
     */
    while(str2[j] != '\0') {
        str1[i++] = str2[j++];
    }
    
    str1[i] = '\0';
    
    printf("After concatenation %s ", str1);
    
    return 0;
}

Output:

Enter a first string :  cprogrammingcode

Enter second string : .com

After concatenation : cprogrammingcode.com

C program to reverse a number

C program to check whether a character is vowel or consonant



No comments:

Post a Comment