Tutorialspoint
Problem
Solution
Submissions

Concatenate Two Strings

Certification: Basic Level Accuracy: 73.33% Submissions: 15 Points: 10

Write a C++ program that concatenates two strings using pointers. The program should take two strings as input and return a new string that concatenates the two input strings.

Example 1
  • Input: string1 = "Hello", string2 = "World"
  • Output: "HelloWorld"
  • Explanation:
    • Step 1: Determine the length of both input strings.
    • Step 2: Allocate memory for the result string (length of string1 + length of string2 + 1 for null terminator).
    • Step 3: Use pointers to copy characters from string1 to the result string.
    • Step 4: Use pointers to append characters from string2 to the result string.
    • Step 5: Add null terminator at the end of the result string.
Example 2
  • Input: string1 = "C++", string2 = "Programming"
  • Output: "C++Programming"
  • Explanation:
    • Step 1: Determine the length of both input strings.
    • Step 2: Allocate memory for the result string (length of string1 + length of string2 + 1 for null terminator).
    • Step 3: Use pointers to copy characters from string1 to the result string.
    • Step 4: Use pointers to append characters from string2 to the result string.
    • Step 5: Add null terminator at the end of the result string.
Constraints
  • 1 ≤ len(string1) ≤ 10^3
  • 1 ≤ len(string2) ≤ 10^3
  • 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) for storing the result
StringsPointers and ReferencesCognizantDropbox
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

  • Use pointers to traverse both strings.
  • Allocate memory for the concatenated string dynamically.
  • Copy characters from both strings to the new string using pointers.

Steps to solve by this approach:

 Step 1: Define a function concatenateStrings that takes two constant character pointers as parameters.

 Step 2: Calculate the lengths of both input strings.
 Step 3: Dynamically allocate memory for the result, big enough to hold both strings plus the null terminator.
 Step 4: Create a pointer to track our position in the result string.
 Step 5: Copy characters from the first string to the result one by one, advancing both pointers.
 Step 6: Copy characters from the second string to the result one by one, advancing both pointers.
 Step 7: Add the null terminator at the end of the result.
 Step 8: Return the pointer to the result string.
 Step 9: In main, call concatenateStrings with two strings, print the result, and free the allocated memory.

Submitted Code :