Click here to Skip to main content
15,882,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Before I roll my own....is there a built-in way in C++ to generate an alphabetical string sequence?

I mean, as an identifier, numerically you might format a string "_001", "_002", "003", etc.

Is there an easy way to generate e.g., "_AAA", "_AAB", "_AAC" etc.?

Cheers,

Dan

What I have tried:

Nothing yet, and it probably won't be too difficult with some ASCII codes and a bit of maths, but I thought I'd ask before I re-invent any wheels.
Posted
Updated 18-May-21 13:17pm

There are several ways other ways to do this but one I like and use a lot involves counting in a different base. It's one way to approach permutations and combinations. In your case, you have 3 digits and each can have 26 values (right?). This means count in base 26, just as you would in decimal or hex. This way can take a lot of memory but not in this case. This will give a table of values (I use a vector to hold arbitrary values) and then you can map each digit's value to a character. Zero becomes 'A', one becomes 'B', and so on. Mathematically, it's character = 'A' + value;

You can do all kinds of combinations and permutations using this technique. For example, you can "deal" a deck of cards. That's a little trickier but not much. For a hand of five cards, each "digit" would have a value of between 0 and 51 and, since it's a deck of cards, no two values can be the same in one hand. That's the difference between combinations and permutations. A hand of cards is a combination and your case is a permutation. The way to think of a hand of cards is it is a deck of 52 combined in sets of 5.
 
Share this answer
 
v2
Comments
Kyudos 18-May-21 22:04pm    
Thanks - my initial thoughts were along the lines of some mod 26 maths :)
This should put "_AAA" through "_ZZZ" into a vector. I haven't tested it, so it might have a bug!
C++
std::string s("_   ");
std::vector<std::string> ids;

for(char c1 = 'A'; c1 <= 'Z'; ++c1)
{
   s[1] = c1;

   for(char c2 = 'A'; c2 <= 'Z'; ++c2)
   {
      s[2] = c2;

      for(char c3 = 'A'; c3 <= 'Z'; ++c3)
      {
         s[3] = c3;
         ids.push_back(s);
      }
   }
}
Is that what you're looking for?
 
Share this answer
 
v5
Comments
Kyudos 18-May-21 18:57pm    
I was wondering if there was some secret formatting trick I didn't know about, but this will certainly do the business.
Greg Utas 18-May-21 18:59pm    
I did test get a chance to test it, so make sure you have the right version! :)

There are probably fancier ways to do it, but I prefer straightforward code.

EDIT: You could also increment s[1], s[2], and s[3], and get rid of c1, c2, and c3.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900