替换字母,但不能替换字符串中的特殊字符和大写字母(Java)

我可以将小写字母替换为下一个字母。特殊字符和大写字母不应更改,但我不知道如何更改。


/** Return s but with each occurrence of a letter in 'a'..'y'

 * replaced by the next letter and 'z' replaced by 'a'

 *

 * Examples: nextChar("") = ""

 * nextChar("abcz") = "bcda"

 * nextChar("1a$b") = "1b$c"

 * nextChar("AB") = "AB"

 * nextChar("love") = "mpwf"   */

public static String nextLetter(String s) {

    // TODO 3

    String next = "";

    for (char x: s.toCharArray()) {

        next += Character.toString((char)(((x - 'a' + 1) % 26) + 'a'));

    }

    return next;

}


浮云间
浏览 161回答 2
2回答

30秒到达战场

只需使用if语句检查该字符是否为小写字母,然后将其提升为下一个字母。该Character类型已经有一个Character.isLowerCase()检查字符是否为小写字母的字符。您还可以进行范围检查,例如if ('a' <= character && character <= 'z')检查字母是否为小写。当您确定字母为小写字母时,将其提升为下一个字母(还请检查字符是否通过'z',然后将其回滚到'a')并将其附加到结果中。如果不是小写字母,则只需将其附加到结果中即可。public class MyClass {&nbsp; &nbsp; public static void main(String args[]) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(nextLetter("abcz1a$bABlove"));&nbsp; &nbsp; }&nbsp; &nbsp; private static String nextLetter(String data) {&nbsp; &nbsp; &nbsp; &nbsp; String result = "";&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < data.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char character = data.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (Character.isLowerCase(character)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; character++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Account for rollover on 'z'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (character == '{') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; character = 'a';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result += character;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; }}结果bcda1b$cABmpwf

千巷猫影

您可以使用if条件来检查字母是否为小写。另外,我使用Java 8 lambda函数来遍历字符串中的字符。public static String nextLetter(String s) {&nbsp; &nbsp; StringBuilder sb = new StringBuilder();&nbsp; &nbsp; s.chars().forEach(c -> {&nbsp; &nbsp; &nbsp; &nbsp; if (Character.isLowerCase(c)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append((char) (((c - 'a' + 1) % 26) + 'a'));&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append((char)c);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return sb.toString();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java