我正在做解码器程序。老师打印的说明说:
小写字符变为大写字符。
大写字符变为小写字符。
数字0-9成为A-J
任何其他字符变为#
哪种方法最简单,最便于打字和阅读?我正在考虑使用if命令,但是:
if(let=a||let=b||let=c); //and so on and so forth, rinse and repeat for uppercase letters.
真的难以理解,只会杀死我的打字手。
答案 0 :(得分:2)
由于这是一项任务,我只是给你一个提示(绝不是唯一的方法,只有一种方式)。你是对的,有更多的程序化方法,这可能会涉及利用chars
很容易转换为数字然后再转回的事实(而Strings
是一点点更难操纵这样)。例如,请查看this页面上的char
到int
地图,看看是否有任何事情发生在你身上......
答案 1 :(得分:1)
在Linux中,我们有tr
命令,它将替换字符
nsaravanas@ubuntu:~$ echo "abcdABCD1234" | tr "a-zA-Z0-9" "A-Za-zA-J"
ABCDabcdBCDE
nsaravanas@ubuntu:~$
在Java
我们可以实现与tr
类似的替换char
public static void main(String[] args) {
String str = "abcdefghABCDEFGHI1234%*@)@*#&";
String from = "a-zA-Z0-9";
String to = "A-Za-zA-J";
final char remaining = '#';
String replaced = tr(from, to, remaining, str);
System.out.println(replaced);
}
private static String tr(String from, String to, char def, String str) {
Map<Character, Character> trMap = buildTRMap(from, to);
return str.chars().mapToObj(ch -> trMap.getOrDefault((char) ch, def) + "").collect(Collectors.joining());
}
private static Map<Character, Character> buildTRMap(String from, String to) {
Map<Character, Character> trMap = new HashMap<>();
for (int i = 0; i < from.length(); i++) {
if (i + 2 < from.length() && from.charAt(i + 1) == '-') {
char fromStart = from.charAt(i);
char fromEnd = from.charAt(i + 2);
char toStart = to.charAt(i);
char toEnd = to.charAt(i + 2);
List<Character> fromL = IntStream.rangeClosed(fromStart, fromEnd).mapToObj(c -> (char) c).collect(Collectors.toList());
List<Character> toL = IntStream.rangeClosed(toStart, toEnd).mapToObj(c -> (char) c).collect(Collectors.toList());
IntStream.range(0, fromL.size()).forEach(in -> trMap.put(fromL.get(in), toL.get(in)));
i += 2;
} else {
trMap.put(from.charAt(i), to.charAt(i));
}
}
return trMap;
}
输出
ABCDEFGHabcdefghiBCDE########
答案 2 :(得分:0)
这可能是现在可以想到的简单解决方案:
for(int i=0;i<str.length();i++){//First it checks for numbers 0-9 and replaces them with characters between A to J, else if alphabets found, converts it to uppercase and lowercase, else convert that character to #
if(str.charAt(i)=='0'){
str.setCharAt(i, 'A');
}else if(str.charAt(i)=='1'){
str.setCharAt(i, 'B');
}else if(str.charAt(i)=='2'){
str.setCharAt(i, 'C');
}else if(str.charAt(i)=='3'){
str.setCharAt(i, 'D');
}else if(str.charAt(i)=='4'){
str.setCharAt(i, 'E');
}else if(str.charAt(i)=='5'){
str.setCharAt(i, 'F');
}else if(str.charAt(i)=='6'){
str.setCharAt(i, 'G');
}else if(str.charAt(i)=='7'){
str.setCharAt(i, 'H');
}else if(str.charAt(i)=='8'){
str.setCharAt(i, 'I');
}else if(str.charAt(i)=='9'){
str.setCharAt(i, 'J');
}else if(Character.isLowerCase(str.charAt(i))){
str.setCharAt(i, Character.toUpperCase(str.charAt(i)));
}else if(Character.isUpperCase(str.charAt(i))){
str.setCharAt(i, Character.toLowerCase(str.charAt(i)));
}else{
str.setCharAt(i, '#');
}
}
答案 3 :(得分:-1)
它有Character.isLowerCase('a')
和Character.toUpperCase('a')
等方法。