For training purposes, I use cstrings in some test programs. I would like to shorten the strings with a placeholder such as "...".
That is, it "Quite a long string"will become "Quite a lo..."if my maximum length is set to 13. In addition, I do not want to destroy the original line - therefore, the shortened line should be a copy.
Below is the (static) method that I am encountering. My question is: If the class allocating memory for my shortened string is also responsible for freeing it? Now I have to save the returned string in a separate “user class” and defer the freeing of memory for this user class.
const char* TextHelper::shortenWithPlaceholder(const char* text, size_t newSize) {
char* shortened = new char[newSize+1];
if (newSize <= 3) {
strncpy_s(shortened, newSize+1, ".", newSize);
}
else {
strncpy_s(shortened, newSize+1, text, newSize-3);
strncat_s(shortened, newSize+1, "...", 3);
}
return shortened;
}