出于教育目的,我在一些测试程序中使用 cstrings。我想用“...”之类的占位符来缩短字符串。
也就是说,如果我的最大长度设置为 13,"Quite a long string"
将变为"Quite a lo..."
。此外,我不想破坏原始字符串 - 因此缩短的字符串必须是副本。
下面的(静态)方法是我想出的。我的问题是:为我的缩短字符串分配内存的类也应该负责释放它吗? 我现在要做的是将返回的字符串存储在单独的“用户类”中,并将内存释放到该用户类。
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;
}