Mastering String Concatenation in C: A Comprehensive Guide

Updated on September 2, 2024

Article Outline

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
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

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

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

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.

Updated on September 2, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

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.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved