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

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

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

#define HI "hello world" char str[] = HI " " HI " " HI; 

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

 "hello world hello world hello world" 

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

 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; } 

现在请记住,这可以提高效率 – 多个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; } 

你可以使用sprintf。

 char s[20] = "Hello"; char s2[20]; sprintf(s2,"%s%s%s",s,s,s); 

http://ideone.com/5sNylW

 #include  #include  int main(void) { char k[100]; gets(k); int lk=strlen(k); int times; scanf("%d",&times); int tl= times*lk; int i,x=0; for(i=lk-1;i 

你可以试着写自己的function。 它也可以使用单长度字符串(即复制单个字符串)。 它使用“string.h”中的函数“strcat()”,所以不要忘记包含这个头。

 char * str_repeat(char str[], unsigned int times) { if (times < 1) return NULL; char *result; size_t str_len = strlen(str); result = malloc(sizeof(char) * str_len + 1); while (times--) { strcat(result, str); } return result; } 

但是,如果您只需要复制字符串进行打印,请尝试使用宏

 #define PRINT_STR_REPEAT(str, times) \ { \ for (int i = 0; i < times; ++i) \ printf("%s", str); \ puts(""); \ } 

结果

 PRINT_STR_REPEAT("-", 10); // ---------- puts(str_repeat("-", 10)); // ---------- PRINT_STR_REPEAT("$", 2); // $$ puts(str_repeat("$", 2)); // $$ PRINT_STR_REPEAT("*\t*", 10); // * ** ** ** ** ** ** ** ** ** * puts(str_repeat("*\t*", 10)); // * ** ** ** ** ** ** ** ** ** * PRINT_STR_REPEAT("*_*", 10); // *_**_**_**_**_**_**_**_**_**_* puts(str_repeat("*_*", 10)); // *_**_**_**_**_**_**_**_**_**_* 

这是一种在C中重复字符串N次的方法。

这是一个字符串“abc”,我想要一个长度为7的字符串,该字符串由重复的字符串组成。

N = 7; 结果:“abcabca”

  while(Index != N){ repeatedString[Index] = oldString[Index%strlen(oldString)]; Index++; } 

重复的String最后是“abcabca”,oldString是“abc”。

我已经根据这篇文章中的早期答案做了这个function。 我在这里分享它,因为之前的一些例子已经被我抛出了段错误

 const char* str_repeat(char* str, size_t times) { if (times < 1) return NULL; char *ret = malloc(sizeof(str) * times + 1); if (ret == NULL) return NULL; strcpy(ret, &str); while (--times > 0) { strcat(ret, &str); } return ret; }