Search code examples
carrayscompareargvstrchr

Finding duplicate chars in argv[]


I'm trying to scan through my arguments list, argv[], and determine if there are duplicate chars. I've tried a few things, but nothing seems to work. I'm really new at C so bear with my horrible code:

char unavailableLetters[26] = "";
int pos = 0;
for(i = 0; i < (argc-1); i++) {
    int size = strlen(argv[i+1]);
    for(j = 0; j < size; j++) {
        char c = argv[i+1][j];

        if(j == 0) {
            unavailableLetters[pos] = c;
            pos+=1;
            } else {

            char *s = strchr (unavailableLetters, c);
            if(s == NULL) {
                unavailableLetters[pos] = c;
                pos += 1;
            }
        }
    }
}

My logic here is to parse through all the arguments and then parse through each character, first checking to see if it is contained in the array of unavailableLetters, and if it is not - add it, and move on. But no matter what I try, they either all get added, or none of them are added. This probably isn't the best way to do it, but I'm out of ideas.

  1. List item

Solution

  • Here is a solution that I tested only briefly. It works with only lowercase letters, and exploits the fact that the ascii values of the letters are consecutive (ascii a is 97 which is why I subtract 97 when assigning an index and add it back when printing out the letter)

    #include <iostream>
    using namespace std;
    
    int main (int argc, char *argv[])
    {
        int letters[26];
    
        for (int i = 0; i < 26; i++) {
            letters[i] = 0;
        }
    
        for (int i = 1; i < argc; i++) {
            cout << "processing word: " << argv[i] << endl;
            char *word = argv[i];
            for (int j = 0; j < strlen(word); j++) {
               cout << "\tprocessing letter: " << word[j] << endl;
               letters[(int)word[j]-97]++;
            }
        }
    
        cout << "Letters that appear only once: " << endl;
        for (int i = 0; i < 26; i++) {
            if (letters[i] == 1)
                cout << (char) (i+97) << endl;
        }
    
        return 0;
    }