java - 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?
解决方案
我不明白您对BufferedReader
or的使用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.
推荐阅读
- c++ - 高性能计算和线程标识符的保存
- html - 我们如何从头开始以角度创建模态弹出窗口
- mysql - 表截断的 Codeigniter 查询
- reactjs - 我可以打印和变量,但我不能用它设置状态并返回错误未定义
- php - file_get_contents 在 CentOS 7 上不起作用
- javascript - w2ui.Grid 中的自定义标题和组标题
- asp.net-core-webapi - 忽略 .NET core 2.2 WebAPI 中响应对象的任何特定大小写
- intellij-idea - Does the flow plugin work with remote debugging in Intellij?
- javascript - 是否可以在解构之前检查对象是否可用?
- javascript - 在 React 中处理基本文档文件下载的最佳方式是什么?