C语言中如何重复一个字符串

2024-01-04

我该如何重复一个字符串? 类似“你好世界”* 3 输出“你好世界你好世界你好世界”


在您的源代码中,无需太多处理,最简单的方法可能是:

#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C语言中如何重复一个字符串 的相关文章

随机推荐