我想知道將字串的單個字符與另一個整個字串進行比較并找到匹配字符的最佳方法。我的代碼中最重要的片段可能是用戶輸入請求:
string text = get_string("text: ");
以及我預定義的“比較”-string=char lowerabc[] = "abcdefghijklmnopqrstuvwxyz";
現在,我想獲取文本的第 n 個值并在 lowerabc 中找到匹配的字符。我的第一次嘗試是使用 for 回圈并將結束條件設定為它們的值匹配時,smth 像這樣:for(int j=0;text[i] == lowerabc[j] ; j ){}
但我發現這比較了兩者的地址,因此沒有意義。因此我偶然發現了 strcmp() 函式并編輯了代碼以匹配零值作為結束標準:for(int j=0;strcmp(text[i], lowerabc[j])==0 ; j ){}但是一旦我編譯它,它就會拋出錯誤:incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]對不起,但似乎我太固執了,無法區分這兩個變數的本質差異,以至于它會對我說這樣的話。因此,因此我想問一下進行此類比較的最有效方法是什么。非常感謝您的幫助
uj5u.com熱心網友回復:
您可以使用strchr()從字串中查找單個字符。
#include <stdio.h>
#include <string.h>
/* mock */
typedef char* string;
string get_string(const char* x) {
static char ret[] = "hoge123abc";
return ret;
}
int main(void) {
string text = get_string("text: ");
char lowerabc[] = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; text[i] != '\0'; i ) {
char* res = strchr(lowerabc, text[i]);
if (res != NULL) {
int idx = res - lowerabc;
printf("%c is found at lowerabc[%d]\n", text[i], idx);
} else {
printf("%c is not found in lowerabc\n", text[i]);
}
}
return 0;
}
輸出:
h is found at lowerabc[7]
o is found at lowerabc[14]
g is found at lowerabc[6]
e is found at lowerabc[4]
1 is not found in lowerabc
2 is not found in lowerabc
3 is not found in lowerabc
a is found at lowerabc[0]
b is found at lowerabc[1]
c is found at lowerabc[2]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/491554.html
上一篇:為什么它告訴我我在比較函式?
