0

I am having a set of number and its corresponding strings

1 -> Shutdown

2 -> Hibernet

3 -> Sleep

4 -> Restart

5 -> Lock

This list can go bigger number mapping to strings

I am curios to know any way we can achieve this by Using C Program, I think if could e easy by map in object oriented C# , C++. I believe it would be difficult to put #define.

The input is integer and returns the corresponding string value. It Would be great help if we can make it very efficient as we may run into this muliple times.

unwind
  • 391,730
  • 64
  • 469
  • 606
PriyabD
  • 21
  • 4

1 Answers1

1

If the numbers are consecutive and close to 0 like you show, the natural solution (in many programming languages) is to use an array:

const char *strings[] = { "Shutdown", "Hibernet", "Sleep", "Restart", "Lock" };

printf("Look, the second string is %s\n", strings[1]);

This will print Hibernet. The only thing to watch out for is that C array indexing is 0-based.

If the numbers are "all over the place" would require a different solution, perhaps a binary tree, or just a sorted array in which you can do binary search. Data types like these are not built into C, you have to use a library or implement them yourself.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • That looks good but that relies to the order of the list, what if we need to have some number different than the order (like some ID that 42-"shutdown") and (102-"Hibernet") I am not sure how that is done in c – Bionix1441 Aug 18 '16 at 08:51