我该如何重复一个字符串? 类似于 "hello world" * 3 输出结果为 "hello world hello world hello world"
我该如何重复一个字符串? 类似于 "hello world" * 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;
}
我基于这篇文章中早期的答案编写了这个函数。 我在这里分享它,因为之前的一些示例会导致段错误。
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;
}
char s[20] = "Hello";
char s2[20];
sprintf(s2,"%s%s%s",s,s,s);
#include <stdio.h>
#include <string.h>
int main(void) {
char k[100];
gets(k);
int lk=strlen(k);
int times;
scanf("%d",×);
int tl= times*lk;
int i,x=0;
for(i=lk-1;i<tl;i++)
{
k[i+1]=k[x];
x++;
}
for(i=0;i<tl;i++)
{
printf("%c",k[i]);
}
return 0;
}
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)); // *_**_**_**_**_**_**_**_**_**_*
while(Index != N){
repeatedString[Index] = oldString[Index%strlen(oldString)];
Index++;
}
当重复的字符串在结尾处为"abcabca",而旧字符串为"abc"。