在 C 中从特定索引动态复制字符串

Copy String from specific index dynamically in C

如果我有

 char str_cp[50],str[50], str_other[50], str_type[50];
 strcpy(str,"how are you : i am fine");
 strcpy(str_other, "who are you : may be robot or human being");
 strcpy(str_type,"type   : worker / manager ");

那么如何编写代码...将字符串从“:”复制到行尾?当我不知道 结束索引。

制作一个大小为 50 的不同数组,然后复制

char source[150]; // supoose your sorce array
char dest[150];   // suppose your destination
int i =0,Flag =0,j=0;

for(char c = source[i];c != '[=10=]';i++)
 {  if(c == ':') 
       Flag = 1; // coz we have to start copying from here

    if(Flag == 1)
      dest[j++]=c; //copying the elements
  }

在 C 中,从特定字符开始复制到字符串末尾,可以使用 strcpy 完成,假设您有足够大的缓冲区。您需要做的就是将指针传递给您要保留的初始字符。

指针可以用strchr找到,像这样:

const char *tail = strchr(str, ':') + 1; // skip ':' itself. Add 2 to skip ' ' too

如果你打印tail,你会得到字符串剩余部分的内容:

printf("%s\n", tail);

如果您需要副本,请使用 strcpy:

size_t len = strlen(tail)+1;
char *copy = malloc(len);
strcpy(copy, tail);
typedef struct string String; //do we suppose you wrote a string buffer
// to avoid mallloc and reallock 
char * d_prs(String * buf; char * to_parse)
{
     reset_st(buf);// do you suppose you have a macro to reset the buffer
     while(*to_parse)
        if(*to_parse++==':') break;
     if(!*to_parse)return NULL;  //if null the str, does not contain ':'
     concat_s(buf,to_parse); //the pointer is right initalized...justcpy
     return str_toCstring(buf);//a macro to get the data of the buffer    

}