有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:如何在字母中进行增量

我将在Java中读取两个字符的字符串。我想确定它的下一个增量是什么。以下是增量的规则

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

因此,如果我读入AC,我将打印出AD

编辑

我可以做一个字符的增量,像这样System.out.println((char) ('C' + 1));。所以我在考虑解析字符串,获取单个字符,只是增加或减少char的值。环绕是什么让我,像AZ->BA。还不确定实现这一目标的最佳方式是什么。你是怎么想的


共 (4) 个答案

  1. # 1 楼答案

    如果是两个字母的话

    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
    }
    

    注:只是一个演示,给你一个基本的想法

  2. # 2 楼答案

    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')});
    }
    
  3. # 3 楼答案

    你有26封信。。。 所以你有一个26*26的范围

    将其解析为整数,然后计算mod(26*26)

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

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

    等等

    然后你可以玩这个数字,并用这些规则解析它