[英]C: How to append/concatenate 'x' spaces to a string
我想在C中的字符串中添加一个可变数量的空格,并希望在我自己实现它之前知道是否有标准的方法。
到现在为止,我用了一些丑陋的方法来做到这一点:
这是我使用的一种方式:
add_spaces(char *dest, int num_of_spaces) {
int i;
for (i = 0 ; i < num_of_spaces ; i++) {
strcat(dest, " ");
}
}
这个性能更好,但看起来也不标准:
add_spaces(char *dest, int num_of_spaces) {
int i;
int len = strlen(dest);
for (i = 0 ; i < num_of_spaces ; i++) {
dest[len + i] = ' ';
}
dest[len + num_of_spaces] = '\0';
}
那么,你有什么标准的解决方案,所以我不重新发明轮子?
我会做
add_spaces(char *dest, int num_of_spaces) {
int len = strlen(dest);
memset( dest+len, ' ', num_of_spaces );
dest[len + num_of_spaces] = '\0';
}
但正如@self所说,一个也获得dest最大大小的函数(包括该示例中的'\\0'
)更安全:
add_spaces(char *dest, int size, int num_of_spaces) {
int len = strlen(dest);
// for the check i still assume dest tto contain a valid '\0' terminated string, so len will be smaller than size
if( len + num_of_spaces >= size ) {
num_of_spaces = size - len - 1;
}
memset( dest+len, ' ', num_of_spaces );
dest[len + num_of_spaces] = '\0';
}
void add_spaces(char *dest, int num_of_spaces) {
sprintf(dest, "%s%*s", dest, num_of_spaces, "");
}
请假设在我调用以下任何函数之前,我注意为我想要连接的空间分配足够的内存
所以在main
假设你声明你的数组像char dest[100]
然后用speces初始化你的字符串。
喜欢
char dest[100];
memset( dest,' ',sizeof(dest));
所以你甚至不需要add_spaces(char *dest, int num_of_spaces)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.