char str[2500] ="int *x = malloc(sizeof(int));";
const char s[9] = "malloc";
char *token = strtok(str, s);
while( token != NULL ) {
printf("%s\n", token );
token = strtok(NULL, s);
}
輸出:
int *x =
(size
f(int));
我希望它回傳:
int *x =
(sizeof(int));
但奇怪的是它拒絕這樣做,我似乎無法弄清楚它為什么這樣做。
編輯:我意識到尺寸太小了,但仍然有問題。
uj5u.com熱心網友回復:
第二個引數strtok是用作分隔符的字串列。它不是用作分隔符的完整字串。因此,您實際上擁有的是字符'm', 'a', 'l', 'o', 和'c'作為分隔符,因此這些字符之一出現的任何地方都會拆分字串。
相反,您想要的是用于strstr搜索子字串。然后您可以使用它從子字串的開頭復制到str開頭,然后再次從子字串的結尾復制到結尾str。
uj5u.com熱心網友回復:
函式 strtok 的第二個引數表示字串中存在的任何字符都可以用作終止字符。
所以這個子串
(sizeof(int))
一旦找到字串“malloc”中出現的字符“o”,就會終止。
您需要使用的是標準的 C 字串函式strstr。它將在源字串中找到子字串“mallpc”,您將能夠輸出“malloc”之前和之后的子字串。
例如
char str[2500] ="int *x = malloc(sizeof(int));";
const char s[9] = "malloc";
char *p = strstr(str, s);
if ( p != NULL )
{
printf( "%.*s\n", ( int )( p - str ), str );
if ( p[strlen( s )] != '\0' ) puts( p );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440255.html
