清單:
該程式采用兩個字串,并顯示出現在任一字串中的字符,沒有雙打。
顯示將按照字符在命令列中出現的順序進行,并且后跟一個 \n。
如果引數數量不是 2,則程式顯示 \n。
代碼:
#include <unistd.h>
int main(int argc, char *argv[])
{
int used[255] = {0};
int i = 1, j = 0;
if(argc == 3)
{
while(i < 3)
{
j = 0;
while(argv[i][j])
{
if(!used[(unsigned char)argv[i][j]])
{
used[(unsigned char)argv[i][j]] = 1;
write(1, &argv[i][j], 1);
}
j ;
}
i ;
}
}
write(1, "\n", 1);
return (0);
}
我理解引數傳遞部分,argv[0] 是程式名,argv[1] 是字串陣列 argv 中的第二個字串,字串是字符陣列,所以 argv[1][0] 是第二個字串中的第一個字符, argv[1][1] 是第二個字串中的第二個字符,依此類推。
但是下面的部分是如何作業的 how is it printing unique characters only once from both arguments?
j = 0;
while(argv[i][j])//while argv[i][j] != '\0'
{
if(!used[(unsigned char)argv[i][j]])
{
used[(unsigned char)argv[i][j]] = 1;
write(1, &argv[i][j], 1);
}
j ;
}
我無法理解邏輯。哪位是C專家,請幫我理解邏輯。謝謝你的幫助。
uj5u.com熱心網友回復:
if(!used[(unsigned char)argv[i][j]])
這是使用 char 作為陣列中的索引。因此,例如,每次獲得字符“e”時,它都會檢查陣列中的索引 101 并查看它是否已被使用。基本上它直接將 ASCII 值映射到陣列。https://theasciicode.com.ar/
如果將代碼分解一下,可能更容易理解:
int index = argv[i][j]; //Use the character's ASCII value as an index.
if(used[index] == 0) //If this character has NOT appeared before
{
used[index] = 1; //Mark this index as "used"
//do stuff with unique character.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373374.html
標籤:C
