最有效的方法是將每個元素迭代爲snprintf
到緩衝區中。
這是一個模擬Python的join()
的函數。
#include <stdio.h>
#define ARRAY_LEN(x) (sizeof(x)/sizeof(x[0]))
/**
* Print an array of unsigned long long integers to a string.
* Arguments:
* buf Destination buffer
* buflen Length of `buf'
* ar Array of numbers to print
* arlen Number of elements in `ar'
* sep Separator string
* Returns:
* The number of bytes printed
*/
int join_ull(char *buf, int buflen,
unsigned long long ar[], int arlen, const char *sep)
{
int i;
char *p;
const char *end = buf + buflen;
/* While we have more elements to print, and have buffer space */
for (i=0, p=buf; i<arlen && p<end; ++i) {
p += snprintf(p, end-p, "%llu%s", ar[i],
(i<arlen-1) ? sep : ""); /* Print separator if not last. */
/* Note that p is advanced to the next place we want to print */
}
return p-buf;
}
int main(void)
{
unsigned long long ar[] = {1, 2, 3};
char buf[1024];
join_ull(buf, sizeof(buf), ar, ARRAY_LEN(ar), " ");
printf("Output: \"%s\"\n", buf);
/* Test the buffer-too-small case */
join_ull(buf, 4, ar, ARRAY_LEN(ar), " ");
printf("Output: \"%s\"\n", buf);
return 0;
}
結果:
Output: "1 2 3"
Output: "1 2"
檢查的sprintf'的返回值()'有多少字符打印。 – timrau 2014-10-01 01:22:55
期望輸出字符串的確切格式是什麼? – 2014-10-01 01:34:25