在您的源代码中,无需太多处理,最简单的方法可能是:
#define HI "hello world"
char str[] = HI " " HI " " HI;
这将声明请求值的字符串:
"hello world hello world hello world"
如果你想code这样就可以了,你可以使用类似的东西:
char *repeatStr (char *str, size_t count) {
if (count == 0) return NULL;
char *ret = malloc (strlen (str) * count + count);
if (ret == NULL) return NULL;
strcpy (ret, str);
while (--count > 0) {
strcat (ret, " ");
strcat (ret, str);
}
return ret;
}
Now keep in mind this can be made more efficient - multiple strcat
operations are ripe for optimisation to avoid processing the data over and over (a). But this should be a good enough start.
您还负责释放此函数返回的内存。
(a) Such as with:
// Like strcat but returns location of the null terminator
// so that the next myStrCat is more efficient.
char *myStrCat (char *s, char *a) {
while (*s != '\0') s++;
while (*a != '\0') *s++ = *a++;
*s = '\0';
return s;
}
char *repeatStr (char *str, size_t count) {
if (count == 0) return NULL;
char *ret = malloc (strlen (str) * count + count);
if (ret == NULL) return NULL;
*ret = '\0';
char *tmp = myStrCat (ret, str);
while (--count > 0) {
tmp = myStrCat (tmp, " ");
tmp = myStrCat (tmp, str);
}
return ret;
}