close
close
check constant dictionary value against string c

check constant dictionary value against string c

3 min read 22-10-2024
check constant dictionary value against string c

Checking Constant Dictionary Values Against Strings in C: A Practical Guide

In C programming, ensuring code robustness often involves validating user input or comparing data against pre-defined values. This is where using constant dictionaries – structures holding key-value pairs – comes in handy. But how do you efficiently check if a given string matches a value within such a dictionary? Let's delve into practical techniques and examples.

Understanding the Challenge

Imagine you're building a system that accepts user-defined status codes, which need to correspond to predefined descriptions. You'd want to ensure the input code maps correctly to the corresponding description within your dictionary.

This challenge is best addressed using a combination of C's strengths:

  • Constants: Ensure unchanging data is protected from accidental modification.
  • Dictionaries: Efficiently store and retrieve data based on keys.
  • String Comparison: Perform accurate and case-sensitive matching.

Solutions and Explanations

Let's explore two popular approaches, each with its pros and cons:

1. Using strcmp and Looping:

This method utilizes the strcmp function to compare strings and iterates through the dictionary to find a matching value.

Code Example (Adapted from GitHub User 'anonymous'):

#include <stdio.h>
#include <string.h>

#define MAX_STATUS_CODES 5

typedef struct {
  const char *code;
  const char *description;
} Status_Code;

const Status_Code status_codes[MAX_STATUS_CODES] = {
  {"OK", "Operation completed successfully"},
  {"ERROR", "An error occurred"},
  {"WARNING", "Potential issues detected"},
  {"INFO", "Informational message"},
  {"PENDING", "Operation is pending"}
};

int main() {
  char userInput[20];
  printf("Enter a status code: ");
  scanf("%s", userInput);

  int found = 0;
  for (int i = 0; i < MAX_STATUS_CODES; i++) {
    if (strcmp(userInput, status_codes[i].code) == 0) {
      printf("Status code '%s' - Description: %s\n", userInput, status_codes[i].description);
      found = 1;
      break;
    }
  }

  if (!found) {
    printf("Invalid status code.\n");
  }

  return 0;
}

Analysis:

  • Pros: Simple and straightforward implementation, easy to understand.
  • Cons: Less efficient for large dictionaries, requires explicit looping through all elements.

2. Using a Hash Table (Adapted from GitHub User 'sdet'):

This approach employs a hash table data structure to store the dictionary, allowing for faster lookups by hashing the string input to find its corresponding value.

Code Example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Simplified hash table implementation
typedef struct {
    char *key;
    char *value;
    struct Node *next;
} Node;

typedef struct {
    Node **table;
    int size;
} HashTable;

HashTable *createHashTable(int size) {
    HashTable *hashTable = malloc(sizeof(HashTable));
    hashTable->size = size;
    hashTable->table = malloc(sizeof(Node *) * size);
    for (int i = 0; i < size; i++) {
        hashTable->table[i] = NULL;
    }
    return hashTable;
}

int hash(char *key, int size) {
    int hash = 0;
    for (int i = 0; key[i] != '\0'; i++) {
        hash += key[i];
    }
    return hash % size;
}

void insert(HashTable *hashTable, char *key, char *value) {
    int index = hash(key, hashTable->size);
    Node *newNode = malloc(sizeof(Node));
    newNode->key = key;
    newNode->value = value;
    newNode->next = hashTable->table[index];
    hashTable->table[index] = newNode;
}

char *lookup(HashTable *hashTable, char *key) {
    int index = hash(key, hashTable->size);
    Node *current = hashTable->table[index];
    while (current != NULL) {
        if (strcmp(current->key, key) == 0) {
            return current->value;
        }
        current = current->next;
    }
    return NULL;
}

int main() {
    HashTable *statusCodes = createHashTable(10);
    insert(statusCodes, "OK", "Operation completed successfully");
    insert(statusCodes, "ERROR", "An error occurred");
    // ... add other status codes

    char userInput[20];
    printf("Enter a status code: ");
    scanf("%s", userInput);

    char *description = lookup(statusCodes, userInput);
    if (description) {
        printf("Status code '%s' - Description: %s\n", userInput, description);
    } else {
        printf("Invalid status code.\n");
    }

    return 0;
}

Analysis:

  • Pros: Faster lookups, particularly for large dictionaries.
  • Cons: More complex implementation, requires understanding hash table concepts.

Choosing the Right Approach

The best solution depends on your specific needs:

  • Small dictionaries: Use strcmp and looping for simplicity.
  • Large dictionaries, performance critical: Utilize a hash table for optimal speed.

Conclusion

Validating strings against constant dictionary values in C is a common task. By choosing an appropriate method – be it direct string comparison or hashing – you ensure data integrity and code robustness. Remember to prioritize readability and choose the approach that best aligns with your project's scale and performance requirements.

Related Posts


Latest Posts