Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Mastering String Concatenation in C: A Comprehensive Guide

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

String concatenation is the process of adding or updating two strings. In the C language, we can add two or more strings end to end or update them using concatenation. It is an essential skill for developing efficient and effective C applications. The modern programming language often provides high-level abstractions for string manipulation; understanding how to perform string concatenations in C is essential for developing efficient, low-level source code.

What is String?

In C programming, Strings are commonly used to manage text and perform various operations. The ‘char’ array stores the string, and functions from the ‘<string.h>’ library facilitate manipulation. Strings in C are a fundamental part of text manipulation and are utilized extensively in a variety of applications, including user input, file handling, and data processing.

 

The following program demonstrates the String in C:

 

Program

#include <stdio.h> #include <string.h> int main() { char str[100]; printf("Enter a string: "); fgets(str, sizeof(str), stdin); str[strcspn(str, "n")] = '0'; printf("You entered: %sn", str); int length = strlen(str); printf("Length of the string: %dn", length); return 0; }

Output

Enter a string: harry You entered: harry Length of the string: 5

How to Append One String to the End of Another

In C language, Appending adds one string to another using the strcat() function. This function concatenates the contents of two strings by attaching the source strings to the end of the destination string to store the result.. The use ‘strcat’ ensures the destination string has sufficient capacity and is properly null-terminated

 

The following program demonstrates the append:

 

Program

#include <stdio.h> #include <string.h> int main() { char str1[50] = "Hello, "; char str2[] = "world!"; strcat(str1, str2); printf("%sn", str1); return 0; }

Output

Hello, world!

Concatenate Two Strings  using the Loop

Concatenating two strings using a loop is fundamental to understanding string manipulation in C. This approach is particularly useful when you want to better understand how strings and arrays work in C Beyond using library functions like ‘strcat’.

 

The following program concatenates two strings in C:

 

Program

#include <stdio.h> int main()  { char name1[20]; char name2[20]; int i; printf("Enter name1: "); scanf("%s",name1); printf("nEnter name2: "); scanf("%s",name2); for(i=0;name1[i]!='0';i++); for(int j=0;name2[j]!='0';j++)  { name1[i]=name2[j]; i++; } name1[i]='0'; printf("The new concatenate string is = : %s", name1); return 0; }

Output 

Enter name1: Neeraj Enter name2: Kumar The ne concatenate string is =: NeerajKumar

Concatenate Two Strings Using a Pointer

We can also concatenate two strings by manipulating pointers and memory directly in C language. This process involves calculating the required memory, copying the characters from each string into a new memory block, and ensuring proper termination of the concatenated result.

 

The following program demonstrates the concatenation of two strings using the two-pointer:

 

Program

#include <stdio.h> #include<string.h> void concatenateStrings(char *dest, const char *src) { while (*dest) { dest++; } while (*src) { *dest = *src; dest++; src++; } *dest = '0'; }   int main() { char str1[150], str2[75]; printf("Enter the first string: "); fgets(str1, sizeof(str1), stdin); str1[strcspn(str1, "n")] = '0';   printf("Enter the second string: "); fgets(str2, sizeof(str2), stdin); str2[strcspn(str2, "n")] = '0'; concatenateStrings(str1, str2); printf("Concatenated string: %sn", str1); return 0; }

Output

Enter the first string: work Enter the second string: tw Concatenated string: worktw
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Concatenate Two Strings Using strcat() Function

String manipulation is a fundamental aspect of programming in the C language, especially when working with text. Concatenation is one of the most common operations, combining two or more strings into a single string. This function is defined in the C standard library.

 

The following program demonstrates the strcat() function:

 

Program

#include <stdio.h> #include <string.h> int main() { char str1[100] = "Hello, "; char str2[] = "World!"; strcat(str1, str2); printf("Concatenated String: %sn", str1); return 0; }

Output

Concatenated string: Voldemort Harry

Concatenate Two Strings without Using Strcat()

String concatenation is a fundamental operation in programming languages. The goal is to combine two or more strings into a single, continuous string. In many programming languages, standard library functions like ‘strcat()’ in C simplify this process.

 

The following program concatenates two strings without using the strcat() function:

 

Program 

#include <stdio.h> #include <stdlib.h> size_t stringLength(const char *str) { size_t length = 0; while (*str++) { length++; } return length; } char* concatenateStrings(const char *str1, const char *str2) { size_t len1 = stringLength(str1); size_t len2 = stringLength(str2);   char *result = (char *)malloc(len1 + len2 + 1); if (result == NULL) { fprintf(stderr, "Memory allocation failedn"); exit(EXIT_FAILURE); } char *ptr = result; while (*str1) { *ptr++ = *str1++; } while (*str2) { *ptr++ = *str2++; } *ptr = '0'; return result; } int main() { const char *str1 = "Neeraj  "; const char *str2 = "Singhaniya"; char *result = concatenateStrings(str1, str2); printf("Concatenated string: %sn", result); free(result); return 0; }

Output

Concatenated string: Neeraj  Singhaniya

 

Also Read: Important Features of C Language

Conclusion

In this article, we learned about the concatenation in C language. It enhances your ability to manipulate and combine text data by understanding and applying various techniques, such as using standard library functions like ‘strcat’ and ‘strcat’ or implementing manual methods. It enables you to write more efficient and robust source code. It is essential to choose the right method for concatenation while being mindful of buffer sizes to prevent overruns. Mastering this technique is a very crucial ability for a C developer. It not only manages text-based data but also contributes to writing higher-quality C programs.

FAQs
The string concatenation in C refers to joining two or more strings end-to-end to form a single, continuous string. This is commonly done using functions from the C standard library or manual methods.
They use the ‘strlen()’ function to check the length of a string. For example, ‘strlen()’.
The use of dynamic memory allocation to handle unknown sizes. Allocate memory with ‘malloc()’ for the concatenated result and free it when done.
Using a function like ‘strncat()’ with dynamically allocated buffers allows you to handle variable sizes more safely. It also ensures you allocate enough space and handle memory reallocation if necessary.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

19 October, 12:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved