C Program to Concatenate Two Strings Without Using strcat - GeeksforGeeks (2024)

Skip to content

  • Tutorials
    • Python Tutorial
      • Python Data Types
      • Python Loops and Control Flow
      • Python Data Structures
      • Python Exercises
    • Java
      • Java Programming Language
        • OOPs Concepts
      • Java Collections
      • Java Programs
      • Java Interview Questions
      • Java Quiz
      • Advance Java
    • Programming Languages
    • System Design
      • System Design Tutorial
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++

Open In App

Last Updated : 19 Feb, 2024

Summarize

Comments

Improve

In C, concatenating two strings means combining two strings to form one string. In this article, we will learn how to concatenate two strings without using the strcat() function in C.

For Example,

Input: 
str1= "Hello,"
str2= "Geek!"

Output:
Concatenated String: Hello, Geek!

Concatenating Two Strings in C

To concatenate two strings without using the strcat() function in C, we need to manually append the characters from the second string to the end of the first string using the following steps:

Approach

  • First, ensure the first string has enough space to hold all characters of the second string (i.e. the size of the first string is the sum of the sizes of both strings).
  • Iterate the first string and find the end where a null-terminator is encountered.
  • Now, copy the second string to the first string starting from the found position.
  • Finally, add a null terminator at the end of the concatenated string.

C Program to Concatenate Two Strings without using strcat()

The below example demonstrates how we can concatenate two strings without using strcat in C.

C

// C program to Concatenate two string without using

// concat()

#include <stdio.h>

// Function to concatenate two strings

void concatenateStrings(char* str1, const char* str2)

{

// Navigate to the end of the first string

while (*str1) {

++str1;

}

// Copy characters of the second string to the end of

// the first string

while (*str2) {

*str1++ = *str2++;

}

// Add the null-terminating character

*str1 = '\0';

}

int main()

{

char string1[50] = "Hello, ";

char string2[] = "Geek!";

// calling function to concatenate strings

concatenateStrings(string1, string2);

// Output the concatenated string

printf("Concatenated String: %s\n", string1);

return 0;

}

Output

Concatenated String: Hello, Geek!

Time Complexity: O(n + m), where n is the length of the first string and m is the length of the second string.
Auxiliary Space: O(1)



fizakhatoon947

C Program to Concatenate Two Strings Without Using strcat - GeeksforGeeks (4)

Improve

Next Article

C program to Compare Two Strings without using strcmp() function

Please Login to comment...

Similar Reads

Write one line functions for strcat() and strcmp() Recursion can be used to do both tasks in one line. Below are one line implementations for stracat() and strcmp(). /* my_strcat(dest, src) copies data of src to dest. To do so, it first reaches end of the string dest using recursive calls my_strcat(++dest, src). Once end of dest is reached, data is copied using (*dest++ = *src++)? my_strcat(dest, s 2 min read strcat() in C C strcat() function appends the string pointed to by src to the end of the string pointed to by dest. It will append a copy of the source string in the destination string. plus a terminating Null character. The initial character of the string(src) overwrites the Null-character present at the end of the string(dest). It is a predefined string handli 2 min read strcat() vs strncat() in C++ strcat() The strcat() function will append a copy of the source string to the end of destination string. The strcat() function takes two arguments: 1) dest 2) src It will append copy of the source string in the destination string. The terminating character at the end of dest is replaced by the first character of src . Return value: The strcat() fun 3 min read C Program to Concatenate Two Strings Using a Pointer In C, concatenation of strings is nothing but it is the process of combining two strings to form a single string. If there are two strings, then the second string is added at the end of the first string. In this article, we are going to learn how to concatenate two strings using a pointer in C. Example: Input: str1 = "Hello"; str2 = " GeeksforGeeks 2 min read How to concatenate two integer arrays without using loop in C ? Given two arrays such that first array has enough extra space to accommodate elements of second array. How to concatenate second array to first in C without using any loop in program? Example: Input: arr1[5] = {1, 2, 3} arr2[] = {4, 5} Output: arr1[] = {1, 2, 3, 4, 5} We strongly recommend you to minimize your browser and try this yourself first. H 1 min read C program to Compare Two Strings without using strcmp() function Given two strings s1 and s2, the task is to write C program compare the two strings without using strcmp() function. If string are equal then print "Equal strings" else print "Unequal strings". Examples: Input: s1 = "geeksforgeeks", s2 = "geeks"Output: Unequal Strings Input: s1 = "geeksforgeeks", s2 = "geeksforgeeks"Output: Equal Strings Approach: 2 min read How to Concatenate Multiple Strings in C? In C, concatenating strings means joining two or more strings end-to-end to form a new string. In this article, we will learn how to concatenate multiple strings in C. Example: Input:char str1[50] = "Hello";char str2[50] = " geeksforgeeks";Output:Hello geeksforgeeks!Concatenating Strings in CTo concatenate strings in C, we can use the strcat functi 1 min read Check if two strings are same or not without using library functions Given two strings S1 and S2, the task is to check whether they are the same or not without using string library functions. Examples: Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksForGeeks”Output: TrueExplanation:S1 and S2 are the same strings Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksforGeeks”Output: False Approach: Follow the steps below to solve the prob 5 min read C/C++ Program to Count number of binary strings without consecutive 1's Write a C/C++ program for a given positive integer N, the task is to count all possible distinct binary strings of length N such that there are no consecutive 1s. Examples: Input: N = 2Output: 3// The 3 strings are 00, 01, 10 Input: N = 3Output: 5// The 5 strings are 000, 001, 010, 100, 101 Recommended: Please solve it on “PRACTICE ” first, before 4 min read C Program to Compare Two Strings Using Pointers In C, strings are arrays of characters terminated by a null character ('\0') and pointers can be used to traverse these arrays and compare the characters in two strings. In this article, we will learn how to compare two strings using pointers in C. For Example, Input:char str1[] = "Hello";char str2[] = "World";Output:Hello and World are not EqualCo 2 min read How to sum two integers without using arithmetic operators in C/C++? Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, --, ...? Method 1 (Using pointers)An interesting way would be: C/C++ Code // May not work with C++ compilers and // may produce warnings in C. // Returns sum of 'a' and 'b' int sum(int a, int b) { char *p = a; return (int)&amp;p[b]; } Despite 4 min read To find sum of two numbers without using any operator Write a program to find sum of positive integers without using any operator. Only use of printf() is allowed. No other library function can be used. Solution It's a trick question. We can use printf() to find sum of two numbers as printf() returns the number of characters printed. The width field in printf() can be used to find the sum of two numbe 9 min read C program to print a string without any quote (single or double) in the program Print a string without using quotes anywhere in the program using C or C++. Note : should not read input from the console. The idea is to use macro processor in C (Refer point 6 of this article). A token passed to macro can be converted to a string literal by using # before it. C/C++ Code // C program to print a string without // quote in the progr 1 min read C Program to Compare Two Strings Lexicographically Here, we will build a C Program to compare two strings lexicographically. Given 2 strings s1 and s2, of lowercase English alphabets, denote the lexicographically greater string. Lexicographical order is the order in which words appear in the order of a dictionary. Input: s1 = "geeks", s2 = "geeksforgeeks Output: String 2 is lexicographically greate 2 min read Program to check if two strings are same or not Given two strings, the task is to check if these two strings are identical(same) or not. Examples: Input: string1 = "GeeksforGeeks", string2 = "GeeksforGeeks" Output: Yes Input: string1 = "Geeks for Geeks", string2 = "Geeks for Geeks" Output: Yes Input: string1 = "GeeksforGeeks", string2 = "Geeks" Output: No Input: string1 = "Geeks for Geeks", stri 7 min read C program to copy string without using strcpy() function strcpy is a C standard library function that copies a string from one location to another. It is defined in the string.h header file. We can use the inbuilt strcpy() function to copy one string to another but here, this program copies the content of one string to another manually without using strcpy() function. Methods to Copy String without using 3 min read C Program to print Fibonacci Series without using loop Given a number N, the task is to print Fibonacci Series till Nth number without using any loop.Examples: Input: N = 5 Output: 0 1 1 2 3Input: N = 10 Output: 0 1 1 2 3 5 8 13 21 34 Method 1: Using goto statement: The goto statement is a jump statement which is sometimes also referred to as unconditional jump statement. It can be used to jump from an 3 min read C Program to Print Number series without using any loop Write a C program for given two number N and K, our task is to subtract a number K from N until number(N) is greater than zero, once the N becomes negative or zero then we start adding K until that number become the original number(N). Note: Not allow to use any loop. Examples : Input : N = 15 K = 5 Output : 15 10 5 0 1 5 10 15 Input : N = 20 K = 6 2 min read Write a C program to print "Geeks for Geeks" without using a semicolon First of all we have to understand how printf() function works. Prototype of printf() function is: int printf( const char *format , ...) Parameter format: This is a string that contains a text to be written to stdout.Additional arguments: ... (Three dots are called ellipses) which indicates the variable number of arguments depending upon the format 2 min read C Program to print numbers from 1 to N without using semicolon? How to print numbers from 1 to N without using any semicolon in C. C/C++ Code #include&lt;stdio.h&gt; #define N 100 // Add your code here to print numbers from 1 // to N without using any semicolon What code to add in above snippet such that it doesn't contain semicolon and prints numbers from 1 to N?We strongly recommend you to minimize yo 2 min read Write a C program to print "GfG" repeatedly without using loop, recursion and any control structure? As we all know the concept of printing the given string repeatedly using various loops(for loop,while loop),recursion and some control structure also. But the question is how we will print the given string repeatedly i.e. infinitely without using any loops,recursion and any control structure? Examples: Input : GFG Output : GFGGFGGFGGFG...(It will p 1 min read C program to print characters without using format specifiers As we know that there are various format specifiers in C like %d, %f, %c etc, to help us print characters or other data types. We normally use these specifiers along with the printf() function to print any variables. But there is also a way to print characters specifically without the use of %c format specifier. This can be obtained by using the be 1 min read C Program For Swapping Nodes In A Linked List Without Swapping Data Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10->15->12->13->20->14, x = 12, y = 20 Output: 4 min read C Program For Printing Reverse Of A Linked List Without Actually Reversing Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorithm: printReverse(head) 1. call print reverse for h 2 min read C# Program For Printing Reverse Of A Linked List Without Actually Reversing Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorithm: printReverse(head) 1. call print reverse for h 2 min read Concatenating Two Strings in C Write a C program to concatenate two strings. String concatenation is the process of joining two strings end-to-end to form a single string. Examples Input: str1 = "Hello", str2 = "World"Output: "HelloWorld"Explanation: Joining "Hello" and "World" results in "HelloWorld". Input: str1 = "Good", str2 = "Morning"Output: "GoodMorning"Explanation: Joini 6 min read Print "Even" or "Odd" without using conditional statement Write a program that accepts a number from the user and prints "Even" if the entered number is even and prints "Odd" if the number is odd. You are not allowed to use any comparison (==, <,>,...etc) or conditional statements (if, else, switch, ternary operator,. Etc). Method 1 Below is a tricky code can be used to print "Even" or "Odd" accordi 4 min read Print 1 to 100 without loop using Goto and Recursive-main Our task is to print all numbers from 1 to 100 without using a loop. There are many ways to print numbers from 1 to 100 without using a loop. Two of them are the goto statement and the recursive main. Print numbers from 1 to 100 Using Goto statement Follow the steps mentioned below to implement the goto statement: declare variable i of value 0decla 5 min read How to deallocate memory without using free() in C? Question: How to deallocate dynamically allocate memory without using “free()” function. Solution: Standard library function realloc() can be used to deallocate previously allocated memory. Below is function declaration of "realloc()" from "stdlib.h" C/C++ Code void *realloc(void *ptr, size_t size); If "size" is zero, then call to realloc is equiva 2 min read Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++? The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Altho 3 min read

Article Tags :

  • C Language
  • C Programs
  • C Examples
  • C-String

Trending in News

View More
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

C Program to Concatenate Two Strings Without Using strcat - GeeksforGeeks (5)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

C Program to Concatenate Two Strings Without Using strcat - GeeksforGeeks (2024)
Top Articles
What happens when estate is the beneficiary of IRA?
Principles of assessment for learning / Assessment for learning / Home
jazmen00 x & jazmen00 mega| Discover
Aadya Bazaar
Mileage To Walmart
Falgout Funeral Home Obituaries Houma
Black Gelato Strain Allbud
Craigslist Pet Phoenix
Encore Atlanta Cheer Competition
Apply A Mudpack Crossword
Slapstick Sound Effect Crossword
Betonnen afdekplaten (schoorsteenplaten) ter voorkoming van lekkage schoorsteen. - HeBlad
Funny Marco Birth Chart
Animal Eye Clinic Huntersville Nc
Gma Deals And Steals Today 2022
Peraton Sso
Jenn Pellegrino Photos
Lancasterfire Live Incidents
Craighead County Sheriff's Department
Mychart Anmed Health Login
Quadcitiesdaily
Boscov's Bus Trips
Company History - Horizon NJ Health
Litter Robot 3 RED SOLID LIGHT
Nesb Routing Number
Inkwell, pen rests and nib boxes made of pewter, glass and porcelain.
Why Are Fuel Leaks A Problem Aceable
Pawn Shop Moline Il
Gen 50 Kjv
Tomb Of The Mask Unblocked Games World
What we lost when Craigslist shut down its personals section
Ice Dodo Unblocked 76
Bad Business Private Server Commands
Urban Blight Crossword Clue
Flaky Fish Meat Rdr2
Arcadia Lesson Plan | Day 4: Crossword Puzzle | GradeSaver
Planet Fitness Lebanon Nh
Elisabeth Shue breaks silence about her top-secret 'Cobra Kai' appearance
Philadelphia Inquirer Obituaries This Week
Wisconsin Women's Volleyball Team Leaked Pictures
Restored Republic May 14 2023
Infinite Campus Farmingdale
The Realreal Temporary Closure
Ladyva Is She Married
Citroen | Skąd pobrać program do lexia diagbox?
Keci News
Doelpuntenteller Robert Mühren eindigt op 38: "Afsluiten in stijl toch?"
Used Curio Cabinets For Sale Near Me
ats: MODIFIED PETERBILT 389 [1.31.X] v update auf 1.48 Trucks Mod für American Truck Simulator
Latest Posts
Article information

Author: Neely Ledner

Last Updated:

Views: 6818

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Neely Ledner

Birthday: 1998-06-09

Address: 443 Barrows Terrace, New Jodyberg, CO 57462-5329

Phone: +2433516856029

Job: Central Legal Facilitator

Hobby: Backpacking, Jogging, Magic, Driving, Macrame, Embroidery, Foraging

Introduction: My name is Neely Ledner, I am a bright, determined, beautiful, adventurous, adventurous, spotless, calm person who loves writing and wants to share my knowledge and understanding with you.