How to concatenate strings in C: a five minute guide
Tags: c, strings, computerscience, programming
Published: 2020-12-21 22:34:44

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. 

**Today, we will go over:**
* [Strings in C refresher](#refresh)
* [How to append one string to the end of another](#how)
* [`strncat` function for appending characters](#strn)
* [More C string questions](#more)
* [What to learn next](#next)

___

<a name="refresh"></a>

## 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. 

<center><h4>char  stringName [stringSize] ;</h4></center>

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

```c
char a[10].
```

And it can be initialized as follows:
* The C program automatically inserts the null character as shown.

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

* A null character is provided by the compiler, implicitly, in the style of initialization as shown.

```c
char  stringName [stringSize] = "Sanjay" ;
```

Let's put these concepts together with two examples. 
```c
#include <stdio.h>

int main () {

   char a[5] = {'H', 'e', 'l', 'l', 'o',};
   printf("String: %s\n", a );
   return 0;
}
```

> **Output:** String: Hello

```c
#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;
}
```

> **Output:** 
> Hello world
> c=p and s=paul

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:

```c
#include <stdio.h>

int main(void) {

  char s[] = "paul";

  printf("s is %ld elements long\n", sizeof(s));

  return 0;
}
```
> **Output:** s is 5 elements long


<br>

### Modifying Strings

In C, it is a bit tricky to modify a declared string.Once a 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

<br>

___

<a name="how"></a>


## 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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rtd5qo6qjev6shz24mev.png)

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

```c
#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;
}
```

> **Output:** Concatenated String: Hello World!



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.

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

> **Output:** Concatenated String: Hello World!


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. 

___

<br>

<a name="strn"></a>

## `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.


```c
#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;
}
```

> **Output:** HelloWorld


> **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:

```c
#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;
}
```

> **Output:** HelloWor

___

<br>

<a name="more"></a>

## 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
* 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


___

## 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 the following:
* Pointers and arrays
* I/O streams
* Debugging in C
* Advanced string modification

To help you with your journey, Educative offers a free course called **[Learn C From Scratch](https://www.educative.io/courses/learn-c-from-scratch)**.  This comprehensive and detailed course will introduce you to all the basic and advanced programming concepts of C language. 

*Happy learning!*

<br>

### Continue reading about C and strings
* [Top 5 advanced C programming concepts for developers](https://www.educative.io/blog/advanced-c-programming-concepts-for-developers)
* [Now is the perfect time to learn C](https://www.educative.io/blog/now-is-the-perfect-time-to-learn-c)
* [Best practices for reversing a string in JavaScript, C++ & Python
](https://www.educative.io/blog/reverse-string-javascript-cpp-python)