The Wayback Machine - https://web.archive.org/web/20240909125850/https://www.geeksforgeeks.org/concatenating-two-strings-in-c/
Open In App

Concatenating Two Strings in C

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Write a C program to concatenate two strings.

String concatenation is the process of joining two strings end-to-end to form a single string.

Examples

Input: str1 = “Hello”, str2 = “World”
Output: “HelloWorld”
Explanation: Joining “Hello” and “World” results in “HelloWorld”.

Input: str1 = “Good”, str2 = “Morning”
Output: “GoodMorning”
Explanation: Joining “Good” and “Morning” results in “GoodMorning”

String Concatenation in C

In C, strcat() function appends the copy of the given source string to another destination string with a NULL character at the end. It is defined inside <string.h> header file in C. It means that the source string characters will be copied to the end of the destination string.

Syntax of strcat()

char *strcat(char *dest, const char *src);

where, src is the string to be appended and dest is the string where src is to be appended.

C Program to Concatenating Two Strings

C
// C Program to concatenate two strings using strcat()
#include <stdio.h>
#include <string.h>

int main() {
    char dest[100] = "Geeksfor";
    char src[100] = "Geeks";

    // Concatenate src to dest
    strcat(dest, src);

    printf("Concatenated String: %s\n", dest);
    return 0;
}

Output
Concatenated String: GeeksforGeeks

Time Complexity: O(n + m) where n and m are the lengths of src and dest respectively.
Auxiliary Space: O(n)

Note: The destination string should be large enough to accommodate the concatenated data to avoid errors.

Different Ways to Concatenate Two Strings in C

Apart from the above straightforward method, there are also other methods in C to concatenate two strings:

1. Concatenating Two Strings Manually Using Loops

We can also concatenate two strings manually using loops that traverse the whole source string and copies each character to the destination string one by one.

  • Find the length of destination string dest.
  • Loop through each character of src and insert it at the end of the dest.
  • Null-terminate the concatenated dest string.

Program to Concatenate Two Strings Manually Using Loops

C
// C Program to concatenate two strings manually using loops
#include <stdio.h>

void concatStr(char *dest, const char *src) {
    int length, j;

    // Find the length of the dest string
    for (length = 0; dest[length] != '\0'; length++);

    // Append the src string to the dest string
    for (j = 0; src[j] != '\0'; j++, length++) {
        dest[length] = src[j];
    }

    // Null-terminate the concatenated dest string
    dest[length] = '\0';
}

int main() {
    char dest[100] = "Geeksfor";
    char src[100] = "Geeks";

    // Call the concatStr function
    concatStr(dest, src);

    printf("Concatenated String: %s\n", dest);
    return 0;
}

Output
Concatenated String: GeeksforGeeks

Time Complexity: O(n + m) where n and m are the lengths of src and dest respectively.
Auxiliary Space: O(n)

When to Use?

Use this method when you need full control over the concatenation process and no dependencies on library functions or you need to do some processing while concatenating.

2. Concatenating Two Strings Using sprintf() Function

The sprintf() function prints the given formatted string to the given string buffer instead of the output console. This method can be used to concatenate two strings by using format specifiers strings.

Syntax of sprintf()

sprintf(buffer, "{formatted_string}", args....);

Program to Concatenate Two Strings Using sprintf() Function

  • Create a temporary string temp.
  • Print both src and dest to the temp string.
  • Copy the contents of the temp string to dest string.
C
// C Program to demonstrate the concatStr function
// using sprintf
#include <stdio.h>
#include <string.h>

void concatStr(char *dest, const char *src) {
  
    // Temporary string buffer
    char temp[200];

    // sprintf call with temp as buffer, and formatted
    // string such  that it concatenates the src to
    // the dest string and store it in temp
    sprintf(temp, "%s%s", dest, src);

    // Seplacing the contents of the dest
    strcpy(dest, temp);
}

int main() {
    char dest[100] = "Geeksfor";
    char src[100] = "Geeks";

    // Call the concatStr function
    concatStr(dest, src);

    printf("Concatenated String: %s\n", dest);
    return 0;
}

Output
Concatenated String: GeeksforGeeks

Time Complexity: O(n + m) where n and m are the lengths of src and dest respectively.
Space Complexity: O(1)

When to use?

This method should be used for complex formatting with concatenation as it supports the C formatted string input.

3. Concatenating Two Strings Using memmove()

The memmove() function from the C standard library can be used to concatenate strings by copying the block of memory of second string to the end of the first string memory.

Syntax of memmove()

memmove(void *dest, const void *src, numBytes);

where numBytes tell the number of bytes to be copied.

Program to Concatenate Two Strings Using memmove()

C
// C Program to demonstrate the concatStr function using memmove
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void concatStr(char *dest, const char *src) {
  
    // Find the length of the first string
    size_t len1 = strlen(dest);
    size_t len2 = strlen(src);

    // Move the second string to the end of the first string
    // +1 to include the null terminator
    memmove(dest + len1, src, len2 + 1);
}

int main() {
    char dest[100] = "Geeksfor";
    char src[100] = "Geeks";

    // Call the concatStr function
    concatStr(dest, src);

    printf("Concatenated String: %s\n", dest);
    return 0;
}

Output
Concatenated String: GeeksforGeeks

Time Complexity: O(n + m) where n and m are the lengths of src and dest respectively.
Space Complexity: O(n)

When to use?

Use when you need an efficient, low-level memory manipulationfor large data copies.

Conclusion

In this article, we explored four different methods to concatenate two strings in C: using the strcat() function, manually using loops, using sprintf(), and using memmove(). Each method has its unique benefits and can be selected depending on the needs of your program, such as whether you require simple concatenation, complex formatting, or efficient memory manipulation.

Frequently Asked Questions on C String Concatenation – FAQs

What is string concatenation?

String concatenation is the process of joining two strings end-to-end to create a single combined string.

Can I concatenate strings without using strcat()?

Yes, you can concatenate strings manually using loops, or by using functions like sprintf() and memmove().

Is there any risk in using strcat()?

Yes, if the destination string is not large enough to hold the combined string, it can lead to buffer overflow errors.

What is the difference between memmove() and strcat() for concatenation?

memmove() is a low-level function that allows efficient memory manipulation, making it useful for large data copies, while strcat() is simpler and more commonly used for basic string concatenation.



Previous Article
Next Article

Similar Reads

C program to Compare Two Strings without using strcmp() function
Given two strings s1 and s2, the task is to write C program compare the two strings without using strcmp() function. If string are equal then print "Equal strings" else print "Unequal strings". Examples: Input: s1 = "geeksforgeeks", s2 = "geeks"Output: Unequal Strings Input: s1 = "geeksforgeeks", s2 = "geeksforgeeks"Output: Equal Strings Approach:
2 min read
Check if two strings are same or not without using library functions
Given two strings S1 and S2, the task is to check whether they are the same or not without using string library functions. Examples: Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksForGeeks”Output: TrueExplanation:S1 and S2 are the same strings Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksforGeeks”Output: False Approach: Follow the steps below to solve the prob
5 min read
C Program to Compare Two Strings Lexicographically
Here, we will build a C Program to compare two strings lexicographically. Given 2 strings s1 and s2, of lowercase English alphabets, denote the lexicographically greater string. Lexicographical order is the order in which words appear in the order of a dictionary. Input: s1 = "geeks", s2 = "geeksforgeeks Output: String 2 is lexicographically greate
2 min read
Program to check if two strings are same or not
Given two strings, the task is to check if these two strings are identical(same) or not. Examples: Input: string1 = "GeeksforGeeks", string2 = "GeeksforGeeks" Output: Yes Input: string1 = "Geeks for Geeks", string2 = "Geeks for Geeks" Output: Yes Input: string1 = "GeeksforGeeks", string2 = "Geeks" Output: No Input: string1 = "Geeks for Geeks", stri
7 min read
C Program to Concatenate Two Strings Without Using strcat
In C, concatenating two strings means combining two strings to form one string. In this article, we will learn how to concatenate two strings without using the strcat() function in C. For Example, Input: str1= "Hello,"str2= "Geek!"Output:Concatenated String: Hello, Geek!Concatenating Two Strings in CTo concatenate two strings without using the strc
2 min read
C Program to Concatenate Two Strings Using a Pointer
In C, concatenation of strings is nothing but it is the process of combining two strings to form a single string. If there are two strings, then the second string is added at the end of the first string. In this article, we are going to learn how to concatenate two strings using a pointer in C. Example: Input: str1 = "Hello"; str2 = " GeeksforGeeks
2 min read
C Program to Compare Two Strings Using Pointers
In C, strings are arrays of characters terminated by a null character ('\0') and pointers can be used to traverse these arrays and compare the characters in two strings. In this article, we will learn how to compare two strings using pointers in C. For Example, Input:char str1[] = "Hello";char str2[] = "World";Output:Hello and World are not EqualCo
2 min read
C Program to Split a String into a Number of Sub-Strings
Splitting a string by some delimiter is a very common task. For example, we have a comma-separated list of items from a file and we want individual items in an array. Almost all programming languages, provide a function split a string by some delimiter.  In C:  // Splits str[] according to given delimiters. // and returns next token. It needs to be
1 min read
C Program to check if strings are rotations of each other or not
Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false) Algorithm: areRotations(str1, str2) 1. Create a temp string and store concatenation of str1 to str1 in temp. temp = str1.str1 2. If str2 is a substring of temp then
3 min read
C/C++ Program to Count number of binary strings without consecutive 1's
Write a C/C++ program for a given positive integer N, the task is to count all possible distinct binary strings of length N such that there are no consecutive 1s. Examples: Input: N = 2Output: 3// The 3 strings are 00, 01, 10 Input: N = 3Output: 5// The 5 strings are 000, 001, 010, 100, 101 Recommended: Please solve it on “PRACTICE ” first, before
4 min read
C Program To Check If A Linked List Of Strings Forms A Palindrome
Given a linked list handling string data, check to see whether data is palindrome or not? Examples: Input: a -&gt; bc -&gt; d -&gt; dcb -&gt; a -&gt; NULL Output: True String "abcddcba" is palindrome. Input: a -&gt; bc -&gt; d -&gt; ba -&gt; NULL Output: False String "abcdba" is not palindrome. Recommended: Please solve it on "PRACTICE" first, befo
2 min read
Storage for Strings in C
In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays C/C++ Code char str[4] = &quot;GfG&quot;; /*One extra for string terminator*/ /* OR */ char str[4] = {‘G’, ‘f’, ‘G’, '&#92;&#48;'}; /* '&#92;&#48;' is string terminator */ When strings are declared as character arrays, they are st
5 min read
C function to Swap strings
Let us consider the below program. C/C++ Code #include&lt;stdio.h&gt; void swap(char *str1, char *str2) { char *temp = str1; str1 = str2; str2 = temp; } int main() { char *str1 = &quot;geeks&quot;; char *str2 = &quot;forgeeks&quot;; swap(str1, str2); printf(&quot;str1 is %s, str2 is %s&quot;, str1, str2); getchar(); return 0; } Outputstr1 is geeks,
2 min read
How to write long strings in Multi-lines C/C++?
Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C/C++ Code #include&lt;stdio.h&gt; int main() { // We can put two double quotes anywhere in a string char
2 min read
Why "&amp;" is not used for strings in scanf() function?
Below is syntax of Scanf. It requires two arguments: scanf("Format Specifier", Variable Address); Format Specifier: Type of value to expect while input Variable Address: &amp;variable returns the variable's memory address. In case of a string (character array), the variable itself points to the first element of the array in question. Thus, there is
2 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Array of Pointers to Strings in C
In C, arrays are data structures that store data in contiguous memory locations. Pointers are variables that store the address of data variables. We can use an array of pointers to store the addresses of multiple elements. In this article, we will learn how to create an array of pointers to strings in C. Array of Pointers to Strings in CAn array of
2 min read
How to Create a Dynamic Array of Strings in C?
In C, dynamic arrays are essential for handling data structures whose size changes dynamically during the program's runtime. Strings are arrays of characters terminated by the null character '\0'. A dynamic array of strings will ensure to change it's size dynamically during the runtime of the program as per the user's needs. In this article, we wil
3 min read
How to Concatenate Multiple Strings in C?
In C, concatenating strings means joining two or more strings end-to-end to form a new string. In this article, we will learn how to concatenate multiple strings in C. Example: Input:char str1[50] = "Hello";char str2[50] = " geeksforgeeks";Output:Hello geeksforgeeks!Concatenating Strings in CTo concatenate strings in C, we can use the strcat functi
1 min read
Array of Strings in C
In C programming String is a 1-D array of characters and is defined as an array of characters. But an array of strings in C is a two-dimensional array of character types. Each String is terminated with a null character (\0). It is an application of a 2d array. Syntax: char variable_name[r][c] = {list of string};Here, var_name is the name of the var
2 min read
C Program to Add 2 Binary Strings
Given two Binary Strings, we have to return their sum in binary form. Approach: We will start from the last of both strings and add it according to binary addition, if we get any carry we will add it to the next digit. Input: 11 + 11Output: 110[GFGTABS] C // C Program to Add 2 Binary Strings // and Print their Binary Sum #include &lt;stdio.h&gt; #i
8 min read
C Program to find whether a no is power of two
Given a positive integer, write a function to find if it is a power of two or not.Examples : Input : n = 4 Output : Yes 22 = 4 Input : n = 7 Output : No Input : n = 32 Output : Yes 25 = 32 1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2. C/C++ Code // C Program to fin
3 min read
Communication between two process using signals in C
Prerequisite : C signal handling In this post, the communication between child and parent processes is done using kill() and signal(), fork() system call. fork() creates the child process from the parent. The pid can be checked to decide whether it is the child (if pid == 0) or the parent (pid = child process id).The parent can then send messages t
3 min read
C Program to Multiply two Floating Point Numbers
Floating point numbers are a way to represent real numbers with both whole parts and fractional parts. In this article, we will learn how to write a C program to find the product of two floating-point numbers. The below image shows an example of floating point multiplication in C: C Program To Multiply Two Floating-Point Numbers The below C program
1 min read
Check whether the two Binary Search Trees are Identical or Not
Given the root nodes of the two binary search trees. The task is to print "Both BSTs are identical" if the two Binary Search Trees are identical else print "Both BSTs are identical". Two trees are identical if they are identical structurally and nodes have the same values. Tree1: 5 / \ 3 8 / \ 2 4 Tree2: 5 / \ 3 8 / \ 2 4 Here in both the trees the
15+ min read
Replace array elements by sum of next two consecutive elements
Given an array arr[] of size n, The task is to replace every element of the array by the sum of next two consecutive elements in a circular manner i.e. arr[0] = arr[1] + arr[2], arr[1] = arr[2] + arr[3], ... arr[n - 1] = arr[0] + arr[1]. Examples: Input: arr[] = {3, 4, 2, 1, 6} Output: 6 3 7 9 7Input: arr[] = {5, 2, 1, 3, 8} Output: 3 4 11 13 7 App
7 min read
C Program to Find Armstrong Numbers Between Two Integers
Prerequisite: Program for Armstrong Numbers A positive integer of n digits is called Armstrong number of order n (order is the number of digits) if abcd… = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + …. Here, we will build a C Program to print Armstrong Numbers between two integers. Example: 153 is an Armstrong number 1*1*1 + 5*5*5 + 3*3*3 = 153 37
3 min read
Find last two remaining elements after removing median of any 3 consecutive elements repeatedly
Given a sequence A1, A2, A3, ... An of distinct integers. The task is to find the last 2 remaining elements after removing the median of any 3 consecutive elements repeatedly from the sequence.Examples: Input: A[] = {2, 5, 3} Output: 2 5 Median of {2, 5, 3} is 3, after removing it the remaining elements are {2, 5}.Input: A[] = {38, 9, 102, 10, 96,
4 min read
Sum of two large Floating-point numbers
Given two very large floating-point numbers in form of large strings str1 and str2, the task is to add the given two numbers. Example: Input: str1 = "584506134.87368350839565308", str2 = "30598657.0330473560587475634983" Output: 615104791.9067308644544006434983 Input: str1 = "38.30", str2 = "37.0983" Output: 75.3983 Approach: To find the addition o
14 min read
Move all zeroes to end of array using Two-Pointers
Given an array of random numbers, Push all the zero’s of the given array to the end of the array. For example, if the given arrays is {1, 0, 2, 6, 0, 4}, it should be changed to {1, 2, 6, 4, 0, 0}. The order of all other elements should be the same.Examples: Input: arr[]={8, 9, 0, 1, 2, 0, 3} Output: arr[]={8, 9, 1, 2, 3, 0, 0} Explanation: Swap {0
6 min read