关于 C 中的 strtok 和令牌
About strtok and tokens in C
所以我有一个关于 strtok 的问题,在 C.Is 中可以使用 strtok 来改造一个字符串,而无需从中删除特定的标记?例如,我有一个从 main 和 argc 获得的字符串, argv.
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 ?
}
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. */
所以我有一个关于 strtok 的问题,在 C.Is 中可以使用 strtok 来改造一个字符串,而无需从中删除特定的标记?例如,我有一个从 main 和 argc 获得的字符串, argv.
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 ?
}
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. */