15,882,278 members
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

## Solution 2

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.

v2
Kyudos 18-May-21 22:04pm
Thanks - my initial thoughts were along the lines of some mod 26 maths :)

## Solution 1

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?

v5
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.

Top Experts
Last 24hrsThis month
 Graeme_Grant 40 OriginalGriff 10 Maciej Los 10 Ebandi 5 Gerardo Gamo -32
 Pete O'Hanlon 1,940 OriginalGriff 1,415 Graeme_Grant 935 Richard Deeming 853 Dave Kreskowiak 694

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