Tutorialspoint
Problem
Solution
Submissions

Concatenate Two Strings

Certification: Basic Level Accuracy: 60% Submissions: 10 Points: 10

Write a C++ program that concatenates two strings without using the `strcat()` function.

Example 1
  • Input: string1 = "Hello", string2 = "World"
  • Output: "HelloWorld"
  • Explanation:
    • Step 1: Create a new string with size equal to the sum of lengths of both input strings.
    • Step 2: Copy characters from the first string to the new string.
    • Step 3: Append characters from the second string to the new string.
    • Step 4: Return the concatenated string.
Example 2
  • Input: string1 = "C++", string2 = "Programming"
  • Output: "C++Programming"
  • Explanation:
    • Step 1: Create a new string with size equal to the sum of lengths of both input strings.
    • Step 2: Copy characters from the first string to the new string.
    • Step 3: Append characters from the second string to the new string.
    • Step 4: Return the concatenated string.
Constraints
  • 1 ≤ len(string1), len(string2) ≤ 10^6
  • The strings contain printable ASCII characters.
  • Time Complexity: O(n + m), where n and m are the lengths of the two strings
  • Space Complexity: O(n + m)
StringsFunctions / MethodsAccentureAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create a new string with enough space to hold both strings.
  • Copy the characters of the first string into the new string.
  • Append the characters of the second string to the new string.

Steps to solve by this approach:

 Step 1: Define a function concatenateStrings that takes a destination character array and a source character pointer.
 Step 2: Initialize two index variables to track positions in both strings.
 Step 3: Find the end of the destination string by locating the null terminator.
 Step 4: Copy characters from source to destination one by one until the source's null terminator.
 Step 5: Add a null terminator at the end of the concatenated string.
 Step 6: In main, call concatenateStrings with two strings and print the result.

Submitted Code :