将数字更改为int数组中的字母,并在Java中返回String [英] Change numbers to letters in a int array and return String in java
本文介绍了将数字更改为int数组中的字母,并在Java中返回String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 int数组(b [])
,该数组具有随机长度和随机整数.我想将小于9的整数保留为整数,我想将数字 9-35
更改为字母 A-Z
.我想在所有高于 35
的数字周围加上()
.因此 b [] = {1,10,36}
将生成一个 String 1A(36)
.我的尝试:
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);
}
推荐答案
我认为这段代码可以完成您的工作.它使用Java-8,StreamAPI:
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);
}
样本输出:
(99)(2)(3)(4)(5)AZO
这篇关于将数字更改为int数组中的字母,并在Java中返回String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文