0

I will be reading in a String of two character in Java. And I want to determine what will be the next increment of it. Below is the rules of increment.

AA -> AB -> AC -> ... -> AZ -> BA -> BB -> ... -> ZZ -> AA

So if I read in AC, I will print out AD.

EDIT

I can do increment of one character, like this System.out.println((char) ('C' + 1));. So I was thinking about parsing the string, get the individual character, just increment or decrement the value of char. The wrap around is what get me, like AZ -> BA. Not sure what the best way to achieve that yet. What are your thought

Thang Pham
  • 38,125
  • 75
  • 201
  • 285
  • 5
    Ok, so what have you tried so far? – Oliver Charlesworth May 19 '11 at 14:52
  • @Oil: I can do increment of one character, like this `System.out.println((char) ('C' + 1));`. So I was thinking about parsing the string, get the individual character, just increment or decrement the value of `char`. The wrap around is what get me, like `AZ` -> `BA`. Not sure what the best way to achieve that yet. What are your thought – Thang Pham May 19 '11 at 14:56
  • This question has been already answered here: http://stackoverflow.com/questions/342052/how-to-increment-a-java-string-through-all-the-possibilities – Miquel May 19 '11 at 14:54

4 Answers4

5
public static String increment(final String p_source) {
    final int first = (p_source.charAt(0) - 'A') * 26;
    final int second = p_source.charAt(1) - 'A';

    final int next = (first + second + 1) % (26*26); 

    return new String(new byte[] {(byte)(next / 26 + 'A'), (byte)(next % 26 + 'A')});
}
Martin Gamulin
  • 3,855
  • 21
  • 25
1

if its 2 letter stuff then

public static String getString(String str){
  String str1 = str;
   str = str.ToLower(); 
  char c1 = str.charAt(0);
  char c2 = str.charAt(1);
  if(c2<Z){
     c2 = c2+1;
  }else{
     c2= 'A';
     if(c1 < z){
      c1 = c1+1;
     }else{
       //you put this thing
     }
  }
     //      return a string concating char
}

Note: just a demonstration , to give you basic idea

jmj
  • 237,923
  • 42
  • 401
  • 438
  • you can compare `char` with a `<` sign like that? And is there a reason that you convert the String to lower case? – Thang Pham May 19 '11 at 15:05
  • @HarryPham yes, and reason is to ignore conflict between `A`,`a` as they have different ascii – jmj May 19 '11 at 15:46
1

You could take the second char from each pair and convert it to ascii, then bump the ascii by one and concatenate it back to the first char. This site shows you how to convert a char to ascii in Java: http://www.roseindia.net/java/java-conversion/CharToASCIIi.shtml

user898763452
  • 169
  • 1
  • 13
1

you have 26 letters... so you have a range of 26*26

Parse it to an int, then calculate mod(26*26)

AA = 0*26^0+0*26^1 = 0

BA = 0*26^0+1*26^1 = 26

etc...

Then you can play that number and parse it with those rules

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185