[英]C String parsing errors with strtok(),strcasecmp()
因此,我是C和整個字符串操作人員的新手,但我似乎無法使strtok()正常工作。 似乎每個人的strtok模板都相同:
char* tok = strtok(source,delim);
do
{
{code}
tok=strtok(NULL,delim);
}while(tok!=NULL);
to do this with the delimiter being the space key, and it seems that strtok() no only reads NULL after the first run (the first entry into the while/do-while) no matter how big the string, but it also seems to wreck the source, turning the source string into the same thing as tok. 因此,我使用分隔符作為空格鍵來執行此操作,並且無論字符串有多大,似乎strtok()不僅在第一次運行(首次輸入while / do-while時)之后都讀取NULL,但是它似乎也破壞了源代碼,將源代碼字符串變成了與tok相同的東西。
這是我的代碼片段:
char* str;
scanf("%ms",&str);
char* copy = malloc(sizeof(str));
strcpy(copy,str);
char* tok = strtok(copy," ");
if(strcasecmp(tok,"insert"))
{
printf(str);
printf(copy);
printf(tok);
}
然后,這是輸入“ insert abcdefg”的輸出
aaabbbcccdddeeefffggg
“插入”似乎完全消失了,我認為這是strcasecmp()的錯誤。 另外,我想指出,我意識到strcasecmp()在我的源字符串中似乎全部用小寫字母表示,我不介意。 Anyhoo,輸入“ insert insert insert”在輸出中絕對不會產生任何結果。 好像這些功能無論“插入”一詞出現了多少次都吃光了。 我可能*僅使用一些C函數逐字符讀取字符串char,但是如果可能的話,我想避免這種情況。 謝謝百萬人,感謝您的幫助。
使用第二段代碼,您會遇到五個問題:第一個問題是scanf
函數的格式是非標准的, 'm'
應該做什么? (例如, 此處是標准功能的良好參考 。)
第二個問題是您在指針上使用了address-of運算符,這意味着您將指針傳遞給了指向scanf
函數的char
(例如char**
)指針的指針。 如您所知, scanf
函數希望將其參數用作指針,但是由於字符串(以字符形式的指針或數組形式的指針)已經是指針,因此您不必對字符串參數使用address-of運算符。
一旦解決了前面的問題,第三個問題就是指針str
未初始化 。 您必須記住,未初始化的局部變量實際上是未初始化的,並且它們的值是不確定的。 實際上,這意味着它們的值似乎是隨機的。 因此str
將指向一些“隨機”內存。
第四個問題是malloc
調用,您在指針上使用sizeof
運算符。 這將返回指針的大小,而不是其指向的大小。
第五個問題,就是當你做strtok
的指針copy
內存的內容,將copy
的初始化。 您為它分配內存(通常是4或8個字節,具體取決於您是在32位還是64位平台上,請參閱第四個問題),但是您永遠不會對其進行初始化。
因此,僅四行代碼就有五個問題。 太好了! ;)
似乎您正在嘗試在單詞“ insert”之后打印3次以空格分隔的令牌。 這是您想要的嗎?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char str[BUFSIZ] = {0};
char *copy;
char *tok;
int i;
// safely read a string and chop off any trailing newline
if(fgets(str, sizeof(str), stdin)) {
int n = strlen(str);
if(n && str[n-1] == '\n')
str[n-1] = '\0';
}
// copy the string so we can trash it with strtok
copy = strdup(str);
// look for the first space-delimited token
tok = strtok(copy, " ");
// check that we found a token and that it is equal to "insert"
if(tok && strcasecmp(tok, "insert") == 0) {
// iterate over all remaining space-delimited tokens
while((tok = strtok(NULL, " "))) {
// print the token 3 times
for(i = 0; i < 3; i++) {
fputs(tok, stdout);
}
}
putchar('\n');
}
free(copy);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.