Home > OS >  How does this code print only unique characters from arguments? (Code Logic)
How does this code print only unique characters from arguments? (Code Logic)

Time:12-06

Checklist:

  • This program takes two strings and displays, without doubles, the characters that appear in either one of the strings.

  • The display will be in the order characters appear in the command line, and will be followed by a \n.

  • If the number of arguments is not 2, the program displays \n.

Code:

#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);
    }

I understand argument passing part that argv[0] is the program name,argv[1] is the second string in the string array argv, and strings are character arrays so argv[1][0] is the first character in the second string, argv[1][1] is the second character in the second string and so on.

but how does the below part works 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  ;
                }

I cannot get the logic. Somebody, who is a C expert, please help me to understand the logic. Thanks for your help.

CodePudding user response:

if(!used[(unsigned char)argv[i][j]])

This is using the char as an index in the array. So for example everytime you get the char 'e' it will check the index 101 in the array and see if it's been used already. Basically it's directly mapping ASCII values to an array. https://theasciicode.com.ar/

It's perhaps easier to understand if you break the code up a bit:

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.
}
  •  Tags:  
  • c
  • Related