替换字符串中指定的字符的switch或replace的实现

替换字符串中指定的字符的switch或replace的实现

package test;

import java.util.Scanner;

public class Test14 {
    public static void main(String[] args) {
        method1();
        method2();
    }

    //1番目の方法
    private static void method1() {
        System.out.println("INPUT STRING : ");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next(); // input value : ABCDEF
        String newStr = str.replace("A", "4")
                .replace("E", "3")
                .replace("G", "6")
                .replace("I", "1")
                .replace("O", "0")
                .replace("S", "5")
                .replace("Z", "2");
        System.out.println(newStr);
    }

    //2番目の方法
    private static void method2() {
        System.out.println("INPUT STRING : ");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            switch (c) {
                case 'A':
                    sb.append("4");
                    break;
                case 'E':
                    sb.append("3");
                    break;
                case 'G':
                    sb.append("6");
                    break;
                case 'I':
                    sb.append("1");
                    break;
                case 'O':
                    sb.append("0");
                    break;
                case 'S':
                    sb.append("5");
                    break;
                case 'Z':
                    sb.append("2");
                    break;
                default:
                    sb.append(c);
                    break;
            }
        }
        System.out.println(sb.toString());
    }
}

上一篇:div文本框的坑(好像富文本编辑器也是这样的)


下一篇:The Rust Programming Language - 第11章 测试 - 11.3 测试的组织结构