我热衷于只对String数组中的数字元素进行排序。我在java中这样做。请帮我解决这个问题。
这是我的问题
对于给定的字符集,只选择整数并按降序对它们进行排序并放入其位置,使其他字符的位置保持不变。 更改的位置应该只是整数而不是其他字符。
示例输入: -
d,1,4,C,9,6
109,87,911,B,645个
77,19,#,95
8,99,14,2,5,6,49
样品输出: -
案例#1:d,9,6,c,4,1
案例#2:911,645,109,b,87
案例#3:95,77,#,。,19
案例#4:99,49,14,8,6,5,2
感谢所有观众。请您帮我解决 Java
中的这个问题这是我的代码,我到目前为止已尝试过。
import java.util.Arrays;
import java.util.Iterator;
import java.util.ArrayList;
class alphaNumeric {
public static void main(String a[]) {
String s1[] = new String[9];
ArrayList l_numList = new ArrayList();
ArrayList l_strList = new ArrayList();
s1[0] = "1000.1";
s1[1] = "100";
s1[2] = "xBC100";
s1[3] = "XBB100";
s1[4] = "TEST";
s1[5] = "AYZ2100";
s1[6] = "99";
s1[7] = "90";
s1[8] = "1000";
System.out.print("Before sorting, numbers are ");
for(int i = 0; i < s1.length; i++)
{
System.out.print(s1[i]+" ");
}
System.out.println();
for (int i = 0; i < s1.length; i++) {
if (isNumber(s1[i])) {
l_numList.add(s1[i]);
} else {
l_strList.add(s1[i]);
}
}
Object[] l_objArray = (Object[]) l_numList.toArray();
int l_intArray[] = new int[l_objArray.length];
for (int i = 0; i < l_objArray.length; i++) {
l_intArray[i] = Integer.parseInt((String) l_objArray[i]);
}
Arrays.sort(l_intArray);
for (int i = 0; i < l_intArray.length; i++) {
System.out.println("after Numsort: " + l_intArray[i]);
}
System.out.print("After sorting, numbers are ");
for(int i = 0; i < l_intArray.length; i++)
{
System.out.print(l_intArray[i]+" ");
}
Object[] l_strArray = (Object[]) l_strList.toArray();
Arrays.sort(l_strArray);
for (int i = 0; i < l_strArray.length; i++) {
System.out.println("after Strsort: " + l_strArray[i]);
}
}
static boolean isNumber(String s) {
String validChars = "0123456789";
boolean isNumber = true;
for (int i = 0; i < s.length() && isNumber; i++) {
char c = s.charAt(i);
if (validChars.indexOf(c) == -1) {
isNumber = false;
} else {
isNumber = true;
}
}
return isNumber;
}
}
答案 0 :(得分:1)
我无法弄清楚你想要做什么,但这就是我要做的事情
工作示例
public class SortOnlyNumbers {
public static void main(String[] args) {
sortOnlyNumbers(new String[] { "d", "1", "4", "c", "9", "6" });
sortOnlyNumbers(new String[] { "109", "87", "911", "b", "645" });
sortOnlyNumbers(new String[] { "77", "19", "#", ".", "95" });
sortOnlyNumbers(new String[] { "8", "99", "14", "2", "5", "6", "49" });
}
private static void sortOnlyNumbers(String[] array) {
List<Integer> indexes = new ArrayList<Integer>();
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
try {
numbers.add(Integer.parseInt(array[i]));
indexes.add(i);
} catch (NumberFormatException e) {
// don't care
}
}
Collections.sort(numbers, Collections.reverseOrder());
for (int i = 0; i < numbers.size(); i++) {
array[indexes.get(i)] = String.valueOf(numbers.get(i));
}
System.out.println(Arrays.toString(array));
}
}
输出
[d, 9, 6, c, 4, 1]
[911, 645, 109, b, 87]
[95, 77, #, ., 19]
[99, 49, 14, 8, 6, 5, 2]