关于C语言中的strtok和令牌

时间:2018-11-18 22:39:05

标签: c string strtok

所以我对C语言中的strtok有疑问。是否可以使用strtok在不删除特定标记的情况下重整字符串?例如,我有一个字符串是通过argc,argv从main获得的。 >

void main(int argc,char *argv[]){
//so i get the string ok let's say its the string my-name-is-Max
//so i want to strtok with "-" so i get the string without the "-" 
//the prob is i can;t seem to reform the string meaning making it 
mynameisMax 

// its just "Max" or "my" sometimes , is there a way i can like combine them 
//together using token method ? 
}

1 个答案:

答案 0 :(得分:1)

strtok对于查找单个角色来说是一个过大的杀伤力。在这种情况下并不能为您服务。如果您想覆盖参数,则只需使用strchr和memmove(因为它们重叠的内存)或strpbrk(如果您搜索一系列字符)即可。

char* s = argv [i];
char* d = argv [i];
char* pos;

while ((pos = strchr (s, '-')) != NULL)
{
    memmove (d, s, pos-s); /* Copy (overlapping) all but the dash */
    d += pos-s;            /* Advance the destination by the copied text. */
    s = pos+1;             /* Advance the source past the dash */
}
memmove (d, s, strlen (s) + 1); /* Copy the rest of the string including the NULL termination. */