Home/Blog/Programming/How to concatenate strings in C: A five-minute guide
Home/Blog/Programming/How to concatenate strings in C: A five-minute guide

How to concatenate strings in C: A five-minute guide

Amanda Fawcett
7 min read

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Modifying strings is an important programming skill. Concatenation involves appending one string to the end of another string.

For example, say we have two strings: “C programming” and “language”. We can use concatenation to generate the output, “C programming language.”

There are a few ways we can append or concatenate strings in C. This quick tutorial teaches you how to concentrate two strings using the strcat() function.

Get hands-on with C today.

Cover
Learn C from Scratch

Do you want to get a grip on the basic programming concepts from scratch? Do you feel the need to have a better and enhanced understanding of how it all works? Well, you've come to the right place. This course outlines data types, control flow, functions, input/output, memory, compilation, debugging and other advanced topics in a comprehensive, yet concise manner. C is where it all begins and where you should also begin to embark on your programming journey. The incredibly efficient and powerful C language forms the basis for many other languages like C++ and Java. It allows you to interact directly with memory and low-level computer operations, thereby enhancing your programming skills and deepening your understanding. This comprehensive and detailed course will introduce you to all the basic and advanced programming concepts of C language. In addition, it also addresses memory, debugging and parallel programming in C. Sounds awesome? Let's dive in!

12hrs
Beginner
6 Challenges
13 Quizzes

Strings refresher in C#

A string is one of the most popular data types in programming. It is a collection of characters grouped together. Under the hood, strings are actually arrays of characters. Just like arrays, we can access string elements through indexing.

The C language can be slightly awkward when it comes to dealing with strings, especially compared to languages like Python. In C, a string is denoted with the help of a character array. A string can be declared with the syntax below.

# char stringName [stringSize] ;

Below, variable a is a character array where you can store up to 10 characters.

char a[10].

And it can be initialized as follows:

  1. The C program automatically inserts the null character as shown to the right.

  2. A null character is provided by the compiler, implicitly, in the style of initialization as seen to the right.

char  stringName [stringSize] = { 'S' , 'a' , 'n' , 'j' , 'a' , 'y' , '\0' } ;
char  stringName [stringSize] = "Sanjay" ;

Let’s put these concepts together with two examples.

#include <stdio.h>
int main () {
char a[5] = {'H', 'e', 'l', 'l', 'o',};
printf("String: %s\n", a );
return 0;
}
#include <stdio.h>
int main(void) {
printf("Hello world\n");
char c = 'p';
char s[] = "paul";
printf("c=%c and s=%s\n", c, s);
return 0;
}

In C, strings are always null-terminated. This means that the last element of the character array is a “null” character, abbreviated \0. When you declare a string as in line 8 above, the compiler does this for you.

Constant character strings are written inside double-quotation marks (see line 5 below), and single character variables are declared using single-quotation marks (see line 7 below).

We can use the sizeof() function to inspect our character string above to see how long it actually is:

#include <stdio.h>
int main(void) {
char s[] = "paul";
printf("s is %ld elements long\n", sizeof(s));
return 0;
}

Modifying Strings#

In C, it is a bit tricky to modify a declared string. Once a string is declared to be a given length, you cannot just make it longer or shorter by reassigning a new constant to the variable.

There are many built-in functions for modifying strings. Consider two strings s1 and s2. Here are few built-in functions that are available in the string.h header file:

  • strlen(s1): returns the length of a string.
  • strcpy(s1, s2): copies string s2 to s1
  • strrev(s1): reverses the given string
  • strcmp(s1, s2): returns 0 if s1 and s2 contain the same string.
  • strcat(s1, s2): concatenates two strings

Learn C from Scrath

Cover
Learn C from Scratch

Do you want to get a grip on the basic programming concepts from scratch? Do you feel the need to have a better and enhanced understanding of how it all works? Well, you've come to the right place. This course outlines data types, control flow, functions, input/output, memory, compilation, debugging and other advanced topics in a comprehensive, yet concise manner. C is where it all begins and where you should also begin to embark on your programming journey. The incredibly efficient and powerful C language forms the basis for many other languages like C++ and Java. It allows you to interact directly with memory and low-level computer operations, thereby enhancing your programming skills and deepening your understanding. This comprehensive and detailed course will introduce you to all the basic and advanced programming concepts of C language. In addition, it also addresses memory, debugging and parallel programming in C. Sounds awesome? Let's dive in!

12hrs
Beginner
6 Challenges
13 Quizzes

String concatenation with C#

String concatenation is the process of combining two or more strings into a single string. There are several ways to perform string concatenation in C, depending on the type of strings or concatenation operators being used and the specific needs of the program. Concatenation operators are syntax elements used to perform this operation on strings. In the C language, there are two concatenation operators that can be used to concatenate strings. These are the plus operator (+) and the compound assignment operator (+=).

When used with strings, the plus operator is also known as the string concatenation operator. It creates a new string by joining two existing strings together. The compound assignment operator is used to concatenate two strings and store the result back in the left-hand side string. This operator is equivalent to using the strcat() function to concatenate strings.

A common method of string concatenation in C is to use string literals. A string literal is a sequence of characters enclosed in double quotes, and is represented as an array of characters in memory. To concatenate two string literals, you can simply place them next to each other within the same set of double quotes. For example:

char* greeting = "Hello, world!";

In this example, the two string literals "Hello, " and “world!” are concatenated to create the string “Hello, world!”.

Another method of string concatenation in C involves using string variables. A string variable directs to a character array stored in memory, and can be used to store a string value. To concatenate two string variables, you can use the strcat() function (more on that function later), which appends the second string to the end of the first string. For example:

#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = "World!";
char result[100];
strcpy(result, str1); // Copy str1 into result
strcat(result, " "); // Add a space to result
strcat(result, str2); // Concatenate str2 to result
printf("%s", result); // Print the concatenated string
return 0;
}

In this example, the strcat() function is used to append the string value of str2 to the end of str1, resulting in the concatenated string “Hello, world!”.

How to append one string to the end of another#

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

The basic process is as follows:

  • Take the destination string
  • Find the NULL character
  • Copy the source string beginning with the NULL character of destination string
  • Append a NULL character to the destination string once copied
widget

Let’s look at an example. Below, the following code will concatenate two strings using the strcat() function:

#include <stdio.h>
#include <string.h>
int main()
{
char destination[] = "Hello ";
char source[] = "World!";
strcat(destination,source);
printf("Concatenated String: %s\n", destination);
return 0;
}

In addition to modifying the original destination string, the strcat() function also returns a pointer to that string. This means that we can directly pass the strcat() function to the printf() function.

#include <stdio.h>
#include <string.h>
int main()
{
char destination[] = "Hello ";
char source[] = "World!";
printf("Concatenated String: %s\n", strcat(destination,source));
return 0;
}

In C, the destination array must be initialized before passing it to strcat. This means that it must have at least 1 location with a NULL character.

strncat function for appending characters#

The strncat function is slightly different. We can use this to append at most n characters from a source string to a destination string. The example below appends the first 5 characters from src at the end of dest (i.e. starting from the NULL character). It then appends a NULL character in the end.

#include <stdio.h>
#include <string.h>
#define DEST_SIZE 40
int main()
{
char src[] = "World Here";
char dest[DEST_SIZE] = "Hello";
strncat(dest, src, 5);
printf(dest);
return 0;
}

Note: The destination array must be large enough to hold the following: the characters of the destination, n characters of the source, and a NULL character.

If the number of characters to copy exceeds the source string, strncat will stop appending when it encounters the NULL character, like below:

#include <stdio.h>
#include <string.h>
#define DEST_SIZE 40
int main()
{
char src[] = "World Here";
char dest[DEST_SIZE] = "Hello";
strncat(dest, src, 3);
printf(dest);
return 0;
}

Appending strings with sprintf()#

Another method for appending strings in C is to use the sprintf() function. The sprintf() function allows you to format a string and store the result. Here is an example of using the sprintf() function to append two strings:

#include <stdio.h>
int main() {
char str1[50] = "Hello";
char str2[50] = "World!";
char result[100];
sprintf(result, "%s %s", str1, str2); // Append str2 to str1
printf("%s", result); // Print the appended string
return 0;
}

The sprintf() function appends the string “world!” to the end of the string "Hello, ". Using pointer arithmetic and the strlen() function to find the end of the destination string, “Hello world!” is now our output.

More C string questions#

There is a lot more we can do with strings in C. Take a look at some of the common interview questions about strings to get a sense of what to learn:

  • Edit all the contents of a string
  • Replace every character of a string with a different character
  • Map every character of one string to another so all occurrences are mapped to the same character
  • Initialize a string in C to an empty string
  • How to preform iteration over a string in C
  • Modify the string so that every character is replaced with the next character in the keyboard
  • Make an array on strings using pointers
  • Convert all the letters in a string to Uppercase letters
  • Convert a string to an integer
  • Splitting a string using strtok() in C

Learn C from Scratch

Cover
Learn C from Scratch

Do you want to get a grip on the basic programming concepts from scratch? Do you feel the need to have a better and enhanced understanding of how it all works? Well, you've come to the right place. This course outlines data types, control flow, functions, input/output, memory, compilation, debugging and other advanced topics in a comprehensive, yet concise manner. C is where it all begins and where you should also begin to embark on your programming journey. The incredibly efficient and powerful C language forms the basis for many other languages like C++ and Java. It allows you to interact directly with memory and low-level computer operations, thereby enhancing your programming skills and deepening your understanding. This comprehensive and detailed course will introduce you to all the basic and advanced programming concepts of C language. In addition, it also addresses memory, debugging and parallel programming in C. Sounds awesome? Let's dive in!

12hrs
Beginner
6 Challenges
13 Quizzes

What to learn next#

Congrats! You should now have a solid idea of how to concatenate two strings in C. It’s a simple process that is important to know for building your foundation. A good next step for your C journey is to learn some advanced C programming concepts like:

  • Pointers and arrays
  • I/O streams
  • Algorithms in C
  • Data structures in C
  • Debugging in C
  • Advanced string modification

To help you with your journey, Educative offers a free course called Learn C From Scratch. This comprehensive and detailed course will introduce you to all the basic and advanced programming concepts of C language.

You’ll learn everything from data types, control flow, functions, input/output, memory, compilation, debugging, and much more.

To continue with C after the basics, try out our Become a C Programmer complete skill path to continue your learning with these advanced C concepts.

Happy learning!

Continue reading about C and strings#

Frequently Asked Questions

How to concatenate a string to itself in C?

Use the strcat() or string.h function to concatenate a string to itself in C.


  

Free Resources