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

use*_*100 1 c

我怎么做重复一个字符串?像"你好世界"*3输出"hello world hello world hello world"

pax*_*blo 13

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

#define HI "hello world"
char str[] = HI " " HI " " HI;
Run Code Online (Sandbox Code Playgroud)

这将声明一个请求值的字符串:

"hello world hello world hello world"
Run Code Online (Sandbox Code Playgroud)

如果你想要代码,你可以使用类似的东西:

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;
}
Run Code Online (Sandbox Code Playgroud)

现在请记住,这可以提高效率 - 多个strcat操作已经成熟,可以优化以避免一遍又一遍地处理数据(a).但这应该是一个很好的开始.

您还负责释放此函数返回的内存.


(a)例如:

// 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;
}
Run Code Online (Sandbox Code Playgroud)