top

Search

C Tutorial

.

UpGrad

C Tutorial

strcat() in C

Overview

The strcat() function in C is defined under the string.h header file. It concatenates two strings (source and destination strings) as parameters and returns the destination string. Ultimately, the destination string has the source and destination strings appended. The strcat full form is "string concatenation," which denotes its purpose of joining two strings by appending the characters of one string to the termination of another.

For instance, if you pass the strings "Let us" and "learn" to the strcat() in C, the function will return "Let us learn".
Importance of strcat() function in C

The following points justify the importance of strcat() function in C.

i. String concatenation:

The strcat() function allows you to efficiently and easily concatenate two strings in C. It lets you dynamically combine strings during runtime. This aspect is beneficial in different scenarios like building complex data structures, constructing file paths, and preparing output messages.

ii. Improved performance and efficiency:

The strcat() function is optimised to achieve efficient string concatenation. It directly adds the source string's characters to the destination string's termination. So, it eliminates the need for huge memory operations or intermediate buffers. Consequently, it leads to enhanced performance when handling huge strings or common concatenation operations.

iii. Increases code readability:

The usage of strcat() makes your code more concise and readable compared to the manual manipulation of strings. The function presents a straightforward syntax for concatenating two strings. Hence, it enhances code maintainability and readability.

iv. Broad compatibility:

The strcat() function is a part of the standard library of C. So, it is broadly available and portable over various compilers and platforms. It guarantees compatibility and consistency in string manipulation operations in diverse C programs.

v. Legacy code support:

Several existing C codebases and libraries depend on strcat() to perform string concatenation. So, the use of this function lets you effectively contribute to legacy codebases.

vi. Flexible integration:

You can easily integrate strcat() with other string manipulation functions. For example, you can integrate it with strlen() to find a string’s length or strcpy() to copy the entered strings before concatenation. Hence, the flexible integration with these functions makes string manipulation operations more versatile.

What is strcat() in C?

The strcat() function in C appends the string pointed to by src (source string) to the end of the string pointed to by dest (destination string). Essentially, it appends a copy of the source string to the destination string. Also, it includes a terminating Null character. In the concatenation process, the initial character of the src string overwrites the null character available at the end of the dest string.

Note that strcat() in C is a predefined string handling function defined under string library <string.h> in C and <cstring> in C++.

It works by searching for the null character ('\0') in the destination string. The null character denotes the end of the string. Subsequently, it copies the characters from the source string to that location. Hence, it effectively extends the destination string.

How to Implement strcat() in C

Let’s take a look at a C program to understand the usage of strcat() in C.

#include <stdio.h>

char* mystrcat(char strg1[50], char strg2[50])
{
int a, length=0;
for(a=0;strg1[a]!='\0';a++) // to get to the end of str1
{
length++;
}
for(a=0;strg2[a]!='\0';a++) // concatenate str2 at the end of str1
{
strg1[length+a] = strg2[a];
}
strg1[length+a]='\0';
return strg1;
}

int main()
{
char string1[25]="Keep";
char string2[25]=" smiling";
char *strg1;
char *strg2;
strg1=string1;
strg2=string2;
printf("%s",mystrcat(strg1,strg2));
}

Output:

In the above code, a custom-made function mystrcat() concatenates two strings strg1 and strg2.

Keep smiling

The strg1 string stores ;keep’ variable and strg2 string stores ‘smiling’ variable. We’ve created two pointers str1 and str2, that point to strg1 and strg2, respectively.

The mystrcat function takes two string pointers and returns a string pointer. In this function, a for loop runs across the string strg1 and increments the value of the length variable until it encounters a null character. Another for loop executes through the second string strg2 until it encounters a null character.

All the characters of strg2 are added to the end of strg1. Lastly, the mystrcat function returns strg1 string pointer.

Syntax of strcat() in C

Syntax of strcat

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

The above syntax uses pointers. You can also use the following simplified form of syntax as below.

strcat(dest,src);

Parameters used in strcat

The strcat() in C accepts two parameters, i.e., ‘dest’ (also called destination string) and ‘src’ (also called source string). These parameters are defined below.

dest:

It is the pointer pointing to the string which will be revised. The string to which the src pointer points to will be copied at the end of the string pointed by the ‘dest’ pointer.

src:

It works as the pointer that points to the string that you want to append to the ‘dest’ string.

Return value of strcat() in C

The strcat() function in C returns a pointer to the destination string (dest).

Exceptions of strcat() in C

The strcat() function in C is specifically designed to concatenate strings, not other data types.

Let’s see what happens when a program tries to concatenate data types other than strings using strcat function.

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

int main()
{
    int m = 150;
    int n = 50;
   
    char str1[20];
    char str2[20];
   
    sprintf(str1, "%d", m);
    sprintf(str2, "%d", n);
   
    strcat(str1, str2);
   
    printf("%s\n", str1);
   
    return 0;
}

Output:

15050

In this example, the integers 'm' and 'n' are converted to strings using sprintf(), and then the strings are concatenated using strcat(). The resulting concatenated string is then printed.

Example Program

Here’s a strcat example in C:

#include <stdio.h>
#include <string.h>
int main()
{
char destination[100] = "Have A";
char source[50] = " Good Morning";
strcat(destination,source);
puts(destination);

return 0;
}

Output:

Have A Good Morning

Explanation:

When implementing the strcat or strcmp in C functions, you must include the string.h header file. In the above code, we have included the string.h header file to use strcat(). Subsequently, we passed src and dest as parameters to this function. The function appends the src string to the dest string. Hence, the dest string is modified.

Simple program demonstrating the use of strcat

You can thoroughly understand the working of strcat through the following simple program.

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

int main()
{
char dest[20] = "Let us";
const char *src1 = " learn";
const char *src2 = " C programming";
strcat(dest, src1);
strcat(dest, src2);
printf("%s\n", dest);
return 0;
}

Output:

Let us learn C programming

In the above program, we have declared a destination array of characters whose size is 20. It is initialised with the string “Let us”. The two source strings, i.e., src1 and src2, work as a pointer to the string “learn” and “C programming”, respectively.

The strcat function concatenates the source string at the end of the destination string. When the strcat function executes as strcat(destination, source), the destination string transforms into "Let us learn C programming". This message is displayed on the console.

Working of strcat

Explanation of how strcat works internally

As seen from the above diagram, the strcat() function accepts two parameters, i.e., str1 and str2. The str2 string will be fully appended to str1 string. This happens with the following syntax of strcat function.

The above syntax shows that the strcat function accepts two arguments, i.e., source and destination.

char *strcat(char *destination, const char *source);

The destination argument points to the null-terminated destination string (the string that will be altered and augmented by appending the characters from the source string). The source argument points to the null-terminated source string (the string that would be appended to the destination string).

During the execution, the strcat function finds the null character ('\0') at the end of the destination string. Subsequently, it copies the characters from the source string to that particular location. Hence, it joins two strings. Note that the strcat function will continue copying characters from the source string until it encounters the null character at the termination of the source string.

Overview of the algorithm used by strcat

The strcat() in C uses an algorithm to concatenate two strings. Here’s an overview of the working of this algorithm.

Step-1: The strcat function accepts two arguments. They are a pointer to the source string (source) and a pointer to the destination string (destination).

Step-2: The algorithm begins its work by searching the null character ('\0') at the end of the destination string. This null character indicates the end of a string.

Step-3: After finding the null character in the destination string, the algorithm starts copying the characters from the source string to the destination string.

Step-4: The algorithm continues copying each character (from the source string to the destination string) until it finds the null character at the last part of the source string.

Step-5: Once all characters are copied from the source string to the destination string, the algorithm appends a null character ('\0') at the extremity of the concatenated string. So, it marks the new termination of the string.

Step-6: Lastly, the strcat function returns a pointer to the final concatenated string. The concatenated string represents the revised destination string.

Note: The destination string should have sufficient space to store the concatenated result. If it’s not sufficiently large to store the concatenated string, it can result in buffer overflows or undefined behaviour.

Differences between strcpy and strcat

Let’s go through strcat vs strcpy:

strcpy()

strcat()

The strcpy() in C is used to copy one string to another. It copies the whole data of the source string to the destination string. Hence, it substitutes the original data of the destination string.

The strcat() in C is used to concatenate two strings. It appends the characters of the source string to the termination of the destination string.

It expects the destination string to have sufficient space to store all the contents of the source string (including the null character).

It expects that the destination string must have sufficient space to store the concatenated result (including the null character).

It ascertains that the destination string is null-terminated by appending a null character ('\0') at the end.

It assumes that the destination string is already null-terminated and adds the source string beginning from the null character.

Conclusion

The strcat() is an extensively used string manipulation function that helps you to combine strings efficiently. When using it, make sure the destination string has adequate space to contain the concatenated result. Properly understanding and correctly using this function can significantly simplify string concatenation tasks in C.

If you aim to reinforce your C fundamentals, then one of the simplest and most effective approaches is going through the tutorials. In addition, pursuing upGrad’s Full Stack Software Development Bootcamp imparts you practical exposure to software development through industry projects. Some of the exceptional perks of this course are interview opportunities, industry projects, Cloud Labs, performance reports, career guidance sessions, etc. The top-notch content delivered by industry leaders facilitates your career advancement in software engineering and STEM!

Enroll now to initiate your journey!

FAQs

1. What must a C programmer keep into account regarding space allocation of the concatenated string?

The strcat function in C doesn’t perform any bounds checking on the destination string. Hence, a C programmer must ensure that sufficient space is allocated to store the concatenated string. Instead, you can use the safer version of this function, i.e., strncat. It allows you to specify a maximum number of characters to concatenate and prevent buffer overflows.

2. Does strcat() alter the source string?

No, strcat() only alters the destination string, but the source string remains unchanged.

3. Can strcat() concatenate more than two strings?

No, strcat() can only concatenate two strings at once. If you want to concatenate multiple strings, you must use multiple invocations of strcat() or implement other string manipulation techniques.

4. What is the return value of strcat()?

The strcat() function returns a pointer to the targte/destination string after performing concatenation.

Leave a Reply

Your email address will not be published. Required fields are marked *