Java 如何获取字母编号并对其进行操作

Java 如何获取字母编号并对其进行操作,java,arrays,string,algorithm,Java,Arrays,String,Algorithm,我有一个要求,当给定字母表和数字时,我需要返回字母表。 如果给出示例,C和4i将返回C+4=G 同样,如果给定C和-2,我将返回C+(-2)=A 如果我有AA,那么AA+4=AD,所以我总是希望从字符串中提取最后一个字符 我曾考虑使用字符串数组来存储字母表,但这似乎是一种糟糕的解决方案。有什么方法可以让我做得更好吗?您不需要将字母存储在数组中;这就是ASCII将所有字母按连续顺序排列的原因之一 执行数学运算,将char隐式转换为int,然后将结果转换为char。你必须检查你没有在“A”之前或“Z

我有一个要求,当给定字母表和数字时,我需要返回字母表。 如果给出示例,C和4i将返回C+4=G 同样,如果给定C和-2,我将返回C+(-2)=A

如果我有AA,那么AA+4=AD,所以我总是希望从字符串中提取最后一个字符


我曾考虑使用字符串数组来存储字母表,但这似乎是一种糟糕的解决方案。有什么方法可以让我做得更好吗?

您不需要将字母存储在数组中;这就是ASCII将所有字母按连续顺序排列的原因之一

执行数学运算,将
char
隐式转换为
int
,然后将结果转换为
char
。你必须检查你没有在“A”之前或“Z”之后


这里有一个。

字母表中的字符都已按顺序排列,您只需在其中添加一个数字即可获得另一个数字

我猜你想要这样的东西:

addToChar('A', 4);

char addToChar(char inChar, int inNum)
{
  return (char)(inChar + inNum);
}
您可能需要检查它是否小于“A”或大于“Z”

回应您的编辑:

void addToChar(char[] inChars, int inNum)
{
   for (int i = inChars.length-1; inNum != 0 && i >= 0; i--)
   {
      int result = inChars[i]-'A'+inNum;
      if (result >= 0)
      {
         inNum = result / 26;
         result %= 26;
      }
      else
      {
         inNum = 0;
         while (result < 0) // there may be some room for optimization here
         {
            result += 26;
            inNum--;
         }
      }
      inChars[i] = (char)('A'+result);
   }
}
请尝试以下示例:

public class example {

 public static void main(String[] args) {

     int number = 2;
     char example = 'c';

     System.out.println((char)(example+number));

    }
 }

你用谷歌搜索过字符集吗?与ASCII一样,字符已经由数字表示

首先,使用强制转换将角色转换为
int
,然后添加
int
,并将其转换回
char
。例如:

char c = 'c';
int cInt = (int)c;
int gInt = cInt + 4;
char g = (char)gInt; // 'G'

这是更新问题的一个示例:

仍然需要验证输入数字和输入字符串(假设数字为124会发生什么情况?)


这还不清楚。你是说你想得到一些函数
foo(charc,inti)
,它为
foo('c',4)
返回
'G'
?如果是这样,那只是
c+i
A
-2
的结果是什么?看起来你不需要存储整个字母表,只需要存储一个字母?!数学表达式能比
+
更复杂吗?一般来说,因为你们想做数学,你们必须确保你们的字母最终被转换成数字,否则你们将无法添加它们。请大家再次检查问题。在否决投票之前。如果
AZ
+1
,会有什么结果?它是
BA
还是
AA
或者其他什么东西(比如例外)?你是对的;我已经编辑了我的答案。包括a可能更正确,因为这是Java使用的question@WarriorPrince再次编辑(正确处理负面输入)。@warriorprice再次编辑(处理溢出)。再次检查问题。EditedIve添加了另一个用新问题更新的答案
char c = 'c';
int cInt = (int)c;
int gInt = cInt + 4;
char g = (char)gInt; // 'G'
 public class example {

 public static void main(String[] args) {

     int number = 1;
     String example = "nicd";
     //get the last letter from the string
     char lastChar = example.charAt(example.length()-1);
     //add the number to the last char and save it
     lastChar = (char) (lastChar+number);
     //remove the last letter from the string
     example = example.substring(0, example.length()-1);
     //add the new letter to the end of the string
     example = example.concat(String.valueOf(lastChar));
     //will print nice
     System.out.println(example);

    }
 }