如何在Java中将一个字母转换为另一个字母 [英] How to convert a letter to an another letter in Java

查看:109
本文介绍了如何在Java中将一个字母转换为另一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个简单的加密程序在Java中将一个字母转换为另一个字母,该程序可以将每个字母按字母顺序缩小一个位置,但字母A除外(A的值为:(0-1)).因此,字母B将变为A,字母C将变为B,字母R将变为Q,依此类推.

I am trying to convert a letter to another letter in Java with a simple encryption program that would convert every letter for one place down the alphabetical scale, with the exception of the letter A (the value of A would be: "(0-1)"). So letter B would turn into A, letter C would turn into B, letter R would turn into Q and so on.

示例:我爱鱼将成为 H knud ehrg

推荐答案

您可以使用以下算法来完成此任务:

You could use something like the following algorithm to accomplish this:

// Our input string.
String input = "I love fish";

// Contains the "encrypted" output string.
StringBuilder encrypted = new StringBuilder();

// Process each character in the input string.
for (char c : input.toCharArray()) {
    if (Character.toLowerCase(c) != 'a' && Character.isLetter(c)) {
        // If the character is a letter that's not 'a', convert it to the previous letter.
        char previous = (char) ((int) c - 1);
        encrypted.append(previous);
    } else {
        // Otherwise just append the original character.
        encrypted.append(c);
    }
}

// Prints the output to stdout.
System.out.println(encrypted.toString());

这篇关于如何在Java中将一个字母转换为另一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆