将字符串中的字母提升为java中的下一个字母

新手上路,请多包涵

我在弄清楚如何让我的代码增加用户输入给出的字符串时遇到问题,这样当用户选择替换像 z 这样的字母时,它会转到 a、b 到 c 等。问题是我有在不使用布尔值的情况下执行此操作。我应该通过使用算术从用户输入中获得从 z 到 a 的提升来得到这个。 Plus 只能是 az 的小写字母。任何帮助将不胜感激谢谢。

原文由 CSD1988 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
1 个回答

这段代码

String foo = "abcdefz";
String bar = "";

for (char c : foo.toCharArray()) {
   bar += Character.toString((char) (((c - 'a' + 1) % 26) + 'a'));
}

System.out.println(bar);

将输出

bcdefga

它所做的是获取字符,减去 ‘a’ 的字符代码,从而给出从 0 到 25 的值。然后我们递增 1。获取该答案并执行模数 26,所以如果我们有 ‘z’,我们减去’a’ 从而得到 25 + 1 = 26,模数 26 = 0。然后我们再次添加 ‘a’,瞧!

** 编辑**

您甚至可以进一步推动这个概念并添加一个变量“移动”值:

 int shiftValue = 12;

String foo = "abcdefz";
String bar = "";

for (char c : foo.toCharArray()) {
   bar += Character.toString((char) (((c - 'a' + shiftValue) % 26) + 'a'));
}

System.out.println(bar);

会输出

mnopqrl

shiftValue 的值可以是任何正整数(即移位-2 与移位24 相同)。试试看。

** 更新**

好吧,只需用等式替换您的 alpha+1 即可。并不是说我想给你所有的东西,但是如果你必须坚持,这是你需要做的:

** 免责声明**:包含您的家庭作业解决方案

// define some constants
char FIRST_LETTER = 'a';    // the first letter in the alphabet
int ALPHABET_SIZE = 26;     // the number of letters in the alphabet
int SHIFT_VALUE = 1;        // number of letters to shift

Scanner kb = new Scanner(System.in);
String second = "hello world";    // target string

String alphabet = kb.next();
// TODO: need to check if alphabet has at least one char and if it's in the range of a-z
char alpha = alphabet.charAt(0);   // just keep the first char in the input
System.out.println(second.replace(alpha, (char) (((alpha - FIRST_LETTER + SHIFT_VALUE) %  ALPHABET_SIZE ) + FIRST_LETTER)));

会输出

l
hemmo wormd

** 编辑 2 **

如果您有一个基于索引的字母表(以防您需要包含额外的字符等),这是另一种解决方案。没有评论也没有优化,但代码有效并且应该是不言自明的……仅供参考:

 int shiftValue = 1;
char[] alphabet = new char[] {
   'a','b','c','d','e','f','g','h','i',
   'j','k','l','m','n','o','p','q','r',
   's','t','u','v','w','x','y','z','!',' '
};
boolean[] replace = new boolean[alphabet.length];

Scanner kb = new Scanner(System.in);
String text = "hello world !";

System.out.print("$ ");
String input = kb.nextLine().toLowerCase();

Arrays.fill(replace, false);
for (char c : input.toCharArray()) {
   int index = -1;
   for (int i=0; i<alphabet.length; i++) {
      if (alphabet[i] == c) {
         index = i;
         break;
      }
   }
   if (index >= 0) {
      replace[index] = true;
   }
}

for (int i=alphabet.length - 1; i>0; i--) {
   if (replace[i]) {
      text = text.replace(alphabet[i], alphabet[(i+shiftValue) % alphabet.length]);
   }
}
System.out.println(text);

自然地,此代码将替换从 --- text 字符串中的标准输入读取的每个字符。输出的一个例子是:

 $ ! e wo
hfllpaxprlda

原文由 Yanick Rochon 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题