Get the next line according to its natural order

In Java, the String class implements Comparable, which means that the String objects are fully ordered. This ordering is called the natural ordering of the class, and the class method compareTois called its natural method of comparison. The set of String objects is also countable in the mathematical sense.

I need a function that takes a string and returns the next one according to the natural ordering of the strings.

For mathematically inclined,

function(X) = Y, where Y is such that: 1) X < Y
                                       2) for all Z, if X < Z, then Y <= Z.

Can you think of a function that does this for strings? (Those that match ^[A-Za-z0-9]+$. I don't care, but you can escape control characters or anything that can cause headaches with encodings is illegal in XML, has line breaks or similar "problematic" characters.)

+3
source share
3 answers
String successor(String s) {
    return s + '\0';
}

Or with your limited alphabet:

String successor(String s) {
    return s + '0';
}

since '0' has the smallest unicode value for all legal characters.

Why do you need this, someone guesses it, though ... perhaps there is a less hacky solution.

+3
source

, , char, 0 ( Java, char - , [0,65535] (§4.2.1)).

// returns the lexicographical successor of a string
public static String successor(String s) {
    return s + "\0";
}

SortedSet String :

. . , , ( ). ( ), , lowEndpoint successor(highEndpoint). , , s - . , s low high, :

SortedSet<String> sub = s.subSet(low, high+"\0");

( ). , s low high, :

SortedSet<String> sub = s.subSet(low+"\0", high);

, - , , (, SortedSet<Number>). API NavigableSet<E>, extends SortedSet<E> , , boolean.

+1

Not sure why you need something like this ... do something? anyway, this is a very primitive solution:


public static String getNextString(String input)
{
  if(input == null || input.trim().length() < 1)
  {
    return("0");
  }
  else
  {
    String trimmed = input.trim();
    int lastPos = input.length()-1;
    int last = (int) input.charAt(lastPos);
    last++;
    if(last > (int) 'z')
    {
      if(lastPos == 0)
      {
        return "00";
      }
      else
      {
        return getNextString(trimmed.substring(0,lastPos-1)) + "0";
      }
    }

  }
}

Obviously, there may be errors, because I just dialed it from my mobile phone on the way home ...

0
source

Source: https://habr.com/ru/post/1761782/


All Articles