Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate string lexicographically larger than input

Tags:

c++

string

std

Given an input string A, is there a concise way to generate a string B that is lexicographically larger than A, i.e. A < B == true?

My raw solution would be to say:

B = A;
++B.back();

but in general this won't work because:

  1. A might be empty
  2. The last character of A may be close to wraparound, in which case the resulting character will have a smaller value i.e. B < A.
  3. Adding an extra character every time is wasteful and will quickly in unreasonably large strings.

So I was wondering whether there's a standard library function that can help me here, or if there's a strategy that scales nicely when I want to start from an arbitrary string.

like image 225
Lorah Attkins Avatar asked Feb 22 '26 05:02

Lorah Attkins


2 Answers

You can duplicate A into B then look at the final character. If the final character isn't the final character in your range, then you can simply increment it by one.

Otherwise you can look at last-1, last-2, last-3. If you get to the front of the list of chars, then append to the length.

like image 192
Joseph Larson Avatar answered Feb 24 '26 19:02

Joseph Larson


You can copy the string and append some letters - this will produce a lexicographically larger result.

    B = A + "a"
like image 23
wreathbro Avatar answered Feb 24 '26 18:02

wreathbro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!