[英]comparing the values in 2 arrays
我有 2 個數組。 一個是字母列表,而另一個是由用戶輸入的。 我正在嘗試編寫一個函數來比較這兩個數組以查看鍵盤是否匹配,例如,如果用戶輸入 BOB,程序會將 BOB 存儲在一個數組中,並將 BOB 與另一個數組進行比較並檢查 BOB 是否在其中。
char bigarray []= "asdlkfjas;ldkfjas;kldf";
printf("Please enter the number of letters: ");
scanf("%d",&dna);
printf("Enter %d characters ", num);
for (int i = 0; i < dna; i++)
{
scanf(" %c", &input[i]);
searchFunc ();
}
一旦我獲得用戶輸入的字符,我就會掃描這些字符並將其存儲在一個數組中。 現在,我的 searchFunc 函數將比較 2 個數組並查看是否存在匹配項並返回其找到位置的索引值。 我不確定如何編寫這個函數來比較值和我必須傳遞的參數。
我相信我需要編寫一個嵌套的 for 循環來遍歷兩個數組,但不完全確定如何去做。
for (int i = 0; i < bigarray []; i++) {
for (int j = 0; j < dna; j++) {
if (bigarray [i] == dna [i])
printf("found at %d", bigarray[i]);
}
}
嵌套循環有效,但標准庫提供了strchr()
它簡化了幾乎正確的代碼。
strchr
函數在s
指向的字符串中定位第一次出現的 c (轉換為字符)。 C11dr §7.24.5.2 2
針對參考字符串搜索用戶輸入的每個字母。
int Compare(const char *ref, const char *user_data, int user_data_length) {
for (int i=0; i<user_data_length; i++) {
if (strchr(ref, user_data[i]) == NULL) return 0; // at least 1 missing
}
return 1; // all found
}
....
printf("All there? %s\n", Compare(bigarray, input, dna) ? "Yes" : "No");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.