我正在尝试用 Java 实现这样的场景。
我有一个ArrayList
["23","5","","","54","20","","","","0"]`
目前,列表尚未排序,我想以保留空字符串 ""
位置的方式对其进行排序。
这意味着空字符串未排序,其他值已排序。 示例 数组列表
["0","5","","","20","23","","","","54"].
请注意,空字符串的位置(最初位于位置 2,3 和 6,7,8 )随后被保留,并且仅对非空值进行排序。我正在使用 Java,我真的很喜欢一些想法来开始实现这个需求。我尝试过谷歌,但找不到这方面的先机。
请帮忙,
提前致谢。
最佳答案
也许是这样的:(感谢Tom提供了有用的链接)
String[] arr = new String[] { "23","5","","","54","20","","","","0" }; // the original array
boolean[] space = new boolean[arr.length]; // indicates whenever the index contains an empty space
String[] target = new String[arr.length]; // the reslted array
for (int i = 0; i < space.length; i++) // init spaces
{
space[i] = arr[i].isEmpty();
}
Arrays.sort(arr); // sort the original array
int index = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i].isEmpty()) continue; // just a space ignore that
index = i; // real values start here
break;
}
for (int i = 0; i < space.length; i++)
{
if (space[i] == true)
{
target[i] = ""; // restore space
}
else
{
target[i] = arr[index]; index++;
}
}
关于java - 需要对字符串值进行排序,同时忽略对空字符串值的任何位置更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27123499/