Search code examples
arrayscloopsuniquec-strings

Check if a string is included in an array and append if not (C)


I have 2 arrays, one called 'edges' which contains a list of city names and another called cityNames which is initialised as an empty string.

What I would like to do is move through the edges array element by element and see if it is included in the cityNames array. If it is, move onto the next element in edges, if it isn't, append the value to the cityNames array.

The code below adds the edges[i].startCity to the cityNames array but it does not check for duplicates and I can't figure out why.

for (int i = 1; i < noEdges; i++) {
        for (int j = 0; j < noCities; j++) {
            if(strcmp(edges[i].startCity, cityNames[j].cityName) != 0) {
                strcpy(cityNames[i].cityName, edges[i].startCity);
            }
        }
        noCities += 1;
    }

Thanks in advance


Solution

  • I will assume that:

    • edges is an array of structures of a known length noEdges, each structure containing a string (either a char pointer or a char array)
    • cityNames is an array of structures for which the size is at least the number of distinct name (it could be noEdges or the size of the edges array)
    • the cityNames structure contain a char array element for which the size is at least the longest name + 1 (+1 for the terminating null)

    Then the following code could give the unique names:

    noCity = 0;
    for (int i = 0; i < noEdges; i++) {
            int dup = 0;       // expect edges[i].startCity not to be a duplicate
            for (int j = 0; j < noCities; j++) {
                if(strcmp(edges[i].startCity, cityNames[j].cityName) == 0) {
                    dup = 1;   // got a duplicate
                    break;     // no need to go further ...
                }
            }
            if (dup == 0) {    // not a duplicate: add it to cityNames
                strcpy(cityNames[noCities].cityName, edges[i].startCity);
                noCities += 1; // we now have one more city
            }
        }
    }