What is the best strategy is for returning a modified copy of a string from a function? From my experience in programming in C, I know that it is generally preferable to return a pointer to a large object (array or struct) instead of a copy.
I have the following example, where I pass a string
type to a C++ function and return a char *
. I was wondering how I should go about returning a string
object instead. If I were to return a string, would it be advisable to return a copy or dynamically allocate it and return the pointer?
#include <iostream>
using namespace std;
char *removeSpaces(string sentence)
{
char *newSentence = new char[sentence.size()]; // At most as long as original
int j = 0;
for (int i = 0; i < sentence.size(); i++) {
if (sentence[i] == ' ') {
newSentence[j++] = ' ';
while (sentence[++i] == ' ');
}
newSentence[j++] = sentence[i];
}
return newSentence;
}
int main(void)
{
string sentence;
cout << "Enter a sentence: ";
getline(cin, sentence);
char *sentenceSpacesRemoved = removeSpaces(sentence);
cout << "After removing spaces: ";
cout << sentenceSpacesRemoved << endl;
delete[] sentenceSpacesRemoved;
return 0;
}