首页 > 解决方案 > How to leave newline unmodified while incrementing/decrementing alphabet characters?

问题描述

I have a string as follows:

String sentence = "I have 20 apples.\n" +
                   "Kevin has 15 apples.\n" +
                   "Peter has nothing."

I want to increment every alphabet characters by 2 leaving other characters(whitespace, special characters, newline etc) unmodified.

Here is a program I wrote.

public static void incrementCharacters(String sentence) {
    BufferedReader reader = new BufferedReader(new StringReader(sentence));
    StringBuilder str = new StringBuilder();

    while((line=reader.readLine()) != null){
        for(int i =0; i < line.length(); i++){
            char ch = line.charAt(i);
            if(Character.isAlphabetic(ch)){
                if(Character.isUpperCase(ch){
                    str.append(Character.toUpperCase((char)(ch + 2)));

                } else {
                    str.append(Character.toLowerCase((char)(ch + 2));           
                }

            } else {
               str.append(ch);
            }

        }

    }
    System.out.println(str);
}

But the output I get is "I have 20 apples.Mgxkp jcu 15 crrngu.Rgvgt icu pqvjkpi." with newline omitted. How can I modify this program so that I have new line included for my output?

标签: java

解决方案


我不明白您对BufferedReaderor的使用Character.toUpperCase()。只需遍历您的字符串,并将每个字符(即一个字母)递增 2 到 aStringBuilder然后将其作为结果返回。

public class MyClass {
    public static void main(String args[]) {
        String sentence = "I have 20 apples.\n" +
                   "My friend has 15 apples.\n" +
                   "My cousin has nothing.";

        System.out.println(incrementCharacters(sentence));           

    }

    public static String incrementCharacters(String sentence) {
        StringBuilder sb = new StringBuilder();
        for (char c : sentence.toCharArray()) {
            sb.append(Character.isLetter(c) ? (char)(c + 2) : (char)c);
        }

        return sb.toString();
    }
}

结果:

K jcxg 20 crrngu.
O{ htkgpf jcu 15 crrngu.
O{ eqwukp jcu pqvjkpi.

推荐阅读