我想连续添加字符串元素,例如 st[]="morty"
,并且我想重复其元素,例如七次。它应该是 st[]="mortymo"
。我写了一个函数,如下所示。 (长度函数为strlen
)。
void repeat(char* st,int n){
int i,k=0,l=length(st);
char* ptr;
ptr=(char*)malloc((n+1)*sizeof(char));
for (i=0;i<n;i++){
*(ptr+i)=*(st+k);
k++;
if(k==l)k=0;
}
}
最佳答案
下面的程序重复原始字符串中的字符。 代码中的注释:
#include<stdio.h>
#include<stdlib.h>
char* repeat(const char* st, size_t n){
// use `const` to note that pointer `st` will not be modified
// for purity you may want to use type `size_t` since returning type of strlen is `size_t`
size_t i, k=0;
size_t l = strlen(st);
// do not use (char *) cast
char* ptr = malloc((n+1)*sizeof(char)); // allocate enough room for characters + NULL
for (i=0; i< n; i++)
{
ptr[i] = st[k]; // use index for readability
k++;
if (k == l)
k=0;
}
ptr[i] = 0; // terminate the string
return ptr;
}
int main( )
{
char *str = "12345";
str = repeat(str, 15);
printf("%s\n",str);
free (str); // free the allocated memory inside the repeat function
return 0;
}
输出:
123451234512345
关于c - C语言中如何连续添加字符串元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47876728/