我想给自己写一个类似于 PHP 的函数str_repeat
。我希望此函数在字符串末尾添加指定数量的字符。
这是一个不起作用的代码 ( string argument 2 expected!
)
void chrrepeat(const char &ch, string &target, const int &count) {
for(int i=0; i<count; i++)
strcat(target, ch);
}
我不完全知道那是什么语言(C++?),但你似乎传递的是一个 charstrcat()
而不是一个以 null 结尾的字符串。这是一个微妙的区别,但strcat
会很高兴地访问更多的无效内存位置,直到找到一个空字节。
而不是使用strcat
效率低下的,因为它必须始终搜索到字符串的末尾,您可以为此创建一个自定义函数。
这是我在 C 中的实现:
void chrrepeat(const char ch, char *target, int repeat) {
if (repeat == 0) {
*target = '\0';
return;
}
for (; *target; target++);
while (repeat--)
*target++ = ch;
*target = '\0';
}
repeat == 0
根据在线手册,我让它返回一个空字符串,因为这就是它在 PHP 中的工作方式。
此代码假定目标字符串拥有足够的空间来进行重复。该函数的签名应该很容易解释,但这里有一些使用它的示例代码:
int main(void) {
char test[32] = "Hello, world";
chrrepeat('!', test, 7);
printf("%s\n", test);
return 0;
}
这打印:
Hello, world!!!!!!!
将字符转换为字符串。
void chrrepeat(char ch, string &target, const int count) {
string help = "x"; // x will be replaced
help[0] = ch;
for(int i=0; i<count; i++)
strcat(target, help);
}