首页 > 解决方案 > 将大型机签名字符转换为Java中相应整数值的最佳方法是什么

问题描述

我有一个场景,如下所示的字符将出现在固定长度的文件中

{ABCDEFGHI = 这组字符分别代表正数0123456789

}JKLMNOPQR = 这组字符分别代表负数0123456789

我需要使用 java 将它们转换为相应的数字 0123456789(正数和负数)。例如:

45{ 应转换为 450 (因为 '{' 表示正 '0' )

45A 应转换为 451(因为 'A' 代表正 '1' )

45B 应转换为 452(因为 'A' 代表正 '2' )

45} 应转换为 -450(因为 '}' 表示负 '0' )

45J 应转换为 -451 (因为 'J' 代表负 '1' )

45K 应转换为 -452(因为 'K' 代表负 '2' )

我在java中不是那么好,所以我使用下面的代码首先使用replace函数将包含上述字符的字符串替换为相应的数字。我知道必须有更好的方法来做到这一点。任何人都可以在这方面给我建议。非常感谢。

public static String replaceChar(String str) {
        if (str.contains("{")) {
            str =  str.replace("{", "0");
        }   
        if (str.contains("A")) {
            str =  str.replace("A", "1");
        }
        if (str.contains("B")) {
            str =  str.replace("B", "2");
        }
        if (str.contains("C")) {
            str =  str.replace("C", "3");
        }
        if (str.contains("D")) {
            str =  str.replace("D", "4");
        }
        if (str.contains("E")) {
            str =  str.replace("E", "5");
        }
        if (str.contains("F")) {
            str =  str.replace("F", "6");
        }
        if (str.contains("G")) {
            str =  str.replace("G", "7");
        }
        if (str.contains("H")) {
            str =  str.replace("H", "8");
        }
        if (str.contains("I")) {
            str =  str.replace("I", "9");
        }
        if (str.contains("J")) {
            str =  str.replace("J", "1");
        }
        return str;
    }

标签: javastr-replace

解决方案


您可以将字母表映射到数字,因为@Tim 已经使用字母作为键和数字作为值,使用正则表达式检查否定性,最后用映射值替换输入字符串中包含的映射键:

public static void main(String[] args) throws IOException {
    System.out.println(convert("45{"));
    System.out.println(convert("45A"));
    System.out.println(convert("45B"));
    System.out.println(convert("45}"));
    System.out.println(convert("45J"));
    System.out.println(convert("45K"));
}
public static long convert(String str){
    String alphabet = "{ABCDEFGHI}JKLMNOPQR";
    Map<String,String> map = Pattern.compile("")
                              .splitAsStream(alphabet)
                              .collect(Collectors.toMap(k->k, k->String.valueOf(alphabet.indexOf(k)%10)));
    boolean isNegative = false;
    if(Pattern.compile("[J-R\\}]+").matcher(str).find()){
        isNegative = true;
    }
    for(String letter : alphabet.split("")){
        str = str.replace(letter, map.get(letter));
    }
    long result = Long.parseLong(str);
    return isNegative ? - result: result;
}

推荐阅读