Copy String C++

Problem

Write a C++ function to copy an existing string. Do not use built in functions.

Solution

This is a straight forward question and to my surprise I was asked this question in a site interview. If you are not prepared you might stumble on the easy ones. The idea is to allocate memory for the new string then copy characters one by one from source to destination.

Code

Here is the code in C++

#include <iostream>

//Function takes input string 
//and return an output string
char* CopyStr(char* input)
{
	int n = 0;

	//Calculate input string length
	while (input[n] != '\0') n++;

	//Allocate memory for new string
	char* out = new char[n];

	//Copy characters from source to destination
	for (int i = 0; i < n; i++) out[i] = input[i];

	return out;
}

void main()
{
	//Sample input
	char* input = "How are you";

	//Call function
	char* out = CopyStr(input);

	//Print output
	std::cout << out << std::endl;
}

Leave a Reply

%d bloggers like this: