[英]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.