我想编写一个类似于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);
}发布于 2013-10-16 20:52:20
我不知道这是什么语言(C++?),但您似乎是在将一个字符传递给strcat(),而不是以空结尾的字符串。这是一个微妙的区别,但是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!!!!!!!发布于 2014-05-01 19:55:18
将字符转换为字符串。
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);
}https://stackoverflow.com/questions/19412834
复制相似问题