我正在嘗試檢查我的文本檔案中是否存在字串,我已經撰寫了一個將檔案內容轉換為字串的函式。
char*read(FILE*f);
我寫的查找字串的函式是:
int find(FILE* f, char* M){
char*chaine=read(f);
if(strstr(chaine, M)!=0){
printf("\n Word exists");
return 0;
}
printf("\nThe word doesn't exist!!");
return -1;
}
文本檔案示例:
嘿,我是初學者 C 學習者。
當我嘗試使用“他”這個詞時,它說這個詞存在。
uj5u.com熱心網友回復:
strstr()正在查找字串,He因為這些字符在Hey. 您可以嘗試使用isalpha()after 來查看它是否是單詞的結尾,或者您是否在另一個單詞中找到了匹配項。
下面是一個使用isalpha()和strlen()如果找到匹配的示例strstr()。
char *example = "Hey I am a beginner C learner.";
char *ia_example = "He, I am a beginner C learner.";
char *to_find = "He";
char *match;
if ((match = strstr(example, to_find)) && !isalpha(match[strlen(to_find)])) {
printf("\"%s\" found in example: \"%s\"\n", to_find, example);
}
if ((match = strstr(ia_example, to_find)) && !isalpha(match[strlen(to_find)])) {
printf("\"%s\" found in ia_example: \"%s\"\n", to_find, ia_example);
}
輸出:
"He" found in ia_example: "He, I am a beginner C learner."
strlen()用于獲取您要搜索的子字串的長度(在本例中He為 length )2。所以match[strlen(to_find)](ie match[2]) 將是匹配子字串之后的字符。如果將該字符放入isalpha()并回傳 false,則您知道子字串匹配后的字符不是任何字符 az 或 AZ。
這將確保您不會像使用"Hey". 請注意,此代碼示例未考慮檢查子字串是否出現在單詞末尾。所以你需要在匹配之前對字符執行類似的檢查,看看是否isalpha()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394536.html
下一篇:我在C中的結構鏈表有問題
