java - 需要对字符串值进行排序,同时忽略对空字符串值的任何位置更改

标签 java string sorting

我正在尝试用 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/

相关文章:

php - 使用 PHP 和 Ajax 对同一页面上的多个结果进行排序

java - Live Copy 上不会自动进行转出

c++ - 通配符匹配递归算法 C++

python - 使用 Python heapq.merge 对大文件进行排序

javascript - 如何找到特定的模式?

c# - 枚举设置为字符串并在需要时获取字符串值

java - 在 ArrayList 中按日期对 ArrayList 列表进行排序

java - 如何获得性能来解码hadoop java代码的符号

Java XML - 当我生成 XML 文件时,Java 将 me ' and "更改为 ' and "

java - JOIN 2 个表并选择特定行