Tutorialspoint
Problem
Solution
Submissions

Copy One String to Another

Certification: Basic Level Accuracy: 53.85% Submissions: 13 Points: 10

Write a C++ program that copies one string to another using pointers. The program should take a string as input and return a new string that is a copy of the input string.

Example 1
  • Input: string = "Programming"
  • Output: "Programming"
  • Explanation:
    • Step 1: Determine the length of the input string.
    • Step 2: Allocate memory for the new string (length + 1 for null terminator).
    • Step 3: Initialize pointers to the first characters of both strings.
    • Step 4: Copy each character from source to destination using pointers.
    • Step 5: Add null terminator at the end of the new string.
Example 2
  • Input: string = "C++"
  • Output: "C++"
  • Explanation:
    • Step 1: Determine the length of the input string.
    • Step 2: Allocate memory for the new string (length + 1 for null terminator).
    • Step 3: Initialize pointers to the first characters of both strings.
    • Step 4: Copy each character from source to destination using pointers.
    • Step 5: Add null terminator at the end of the new string.
Constraints
  • 1 ≤ len(string) ≤ 10^3
  • String contains printable ASCII characters
  • Time Complexity: O(n) where n is the length of the string
  • Space Complexity: O(n) for storing the result
StringsPointers and ReferencesTutorialspointWalmart
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 the source string.
  • Allocate memory for the destination string dynamically.
  • Copy characters from the source string to the destination string using pointers.

Steps to solve by this approach:

 Step 1: Define a function copyString that takes a constant character pointer as parameter.

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

Submitted Code :