c - C语言中如何连续添加字符串元素?

标签 c string function repeat

我想连续添加字符串元素,例如 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/

相关文章:

excel - 间接函数返回#REF

c - 循环中的空间局部性

c - 卡在 C 中的赋值上

java - 将充满数字的文本文档翻译成文字

c++ - 操作字符串 C++

r - 如何使用数据框中的变量创建函数

c - 我的 arm-none-eabi-gcc 在 stm32 上的项目有什么问题?

c++ - 指向二维数组的指针的 C/C++ 数组

java - Java 中的字符串标记化(大文本)

function - 如何检查Azure Function是否仍在运行