Som*_*ing 12 c string spaces concatenation
我想在C中的字符串中添加一个可变数量的空格,并希望在我自己实现它之前知道是否有标准的方法.
到现在为止,我用了一些丑陋的方法来做到这一点:
这是我使用的一种方式:
add_spaces(char *dest, int num_of_spaces) {
int i;
for (i = 0 ; i < num_of_spaces ; i++) {
strcat(dest, " ");
}
}
Run Code Online (Sandbox Code Playgroud)
这个性能更好,但看起来也不标准:
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';
}
Run Code Online (Sandbox Code Playgroud)
那么,你有什么标准的解决方案,所以我不重新发明轮子?
我会做
add_spaces(char *dest, int num_of_spaces) {
int len = strlen(dest);
memset( dest+len, ' ', num_of_spaces );
dest[len + num_of_spaces] = '\0';
}
Run Code Online (Sandbox Code Playgroud)
但正如@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';
}
Run Code Online (Sandbox Code Playgroud)