Change numbers to letters in a int array and return String in java

让人想犯罪 __ 提交于 2021-01-04 07:27:25

问题


I have an int array (b[]) with a random length and random integers. I want to leave integers lower than 9 to how they are, i want to change the numbers 9-35 to letters A-Z. and i want do put () around all numbers higher than 35. So b[] = {1,10,36} would generate a String 1A(36). My try:

int b[] = {99, 2, 3, 4, 5, 10, 35, 24};  //sample input
char[] hilfsarray = new char[b.length];
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVW".toCharArray();

for (int k = 0; k < hilfsarray.length; k++) //overwrite all positons with *
    hilfsarray[k] = '*';

for (int i = 0; i < b.length; i++) {
    int p = b[0] - 10;
    if (b[i] < 9 && b[i] <= 35) {
        hilfsarray[i] = alphabet[p];
    }
    return Arrays.toString(hilfsarray);
}

回答1:


I think this code will do your job. It uses Java-8, StreamAPI:

public String someMethod() {
    int[] items = {99, 2, 3, 4, 5, 10, 35, 24}; // sample input
    String[] alphabet =
            "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(",");

    return Arrays.stream(items)
            .mapToObj(item -> (item > 9 && item <= 35) ?
                    alphabet[item - 10] : "(" + item + ")")
            .reduce("", String::concat);
}

Sample output:

(99)(2)(3)(4)(5)AZO



回答2:


You can interpret numbers in the range 10-35 as characters and shift their code points by 55 to get code points of uppercase letters 65-90:

public static void main(String[] args) {
    int[] a = {1, 10, 36};
    int[] b = {99, 2, 3, 4, 5, 10, 35, 24};

    System.out.println(custom(a)); // 1A(36)
    System.out.println(custom(b)); // (99)2345AZO
}
public static String custom(int[] arr) {
    return Arrays.stream(arr).mapToObj(i -> {
        if (i > 9 && i < 36)
            return Character.toString(i + 55);
        else if (i > 35)
            return "(" + i + ")";
        else
            return String.valueOf(i);
    }).collect(Collectors.joining());
}

See also: Replace non ASCII character from string



来源:https://stackoverflow.com/questions/65130666/change-numbers-to-letters-in-a-int-array-and-return-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!