December 21, 2010
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++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#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; } |