【问题标题】:Java Program to sort string of arraysJava程序对数组字符串进行排序
【发布时间】:2021-03-21 11:50:12
【问题描述】:
public class App {

    public static void main(String[] args) {


        getWords("i m very very happy");

    }

    private static TreeSet<String> getWords(String str) {

        char a[] = str.toCharArray();
        String smallWords = "";
        List<String> words = new ArrayList<>();

        for (int i = 0; i < a.length; i++) {

            if (a[i] != ' ') {
                smallWords = smallWords + a[i];
            } else {
                char sortedA[] = smallWords.toCharArray();
                Arrays.sort(sortedA);
                String sortedString = new String(sortedA);
                words.add(sortedString);
                smallWords = "";
            }

        }

        System.out.println("words :: " + words);
        TreeSet<String> sortedWords = new TreeSet<>(words);
        System.out.println("sortedWords :: " + sortedWords);
        return sortedWords;
    }
}

在上面的代码中,我能够使用按字符串数组排序的每个单词来编写正确的输出,但我的输出是 [ervy, i, m],其中最后一个单词 happy 丢失了。有人可以指导我必须使用什么逻辑,因此数组的最后一个字也应该反映在我的输出中。

【问题讨论】:

  • sortedString 添加到words 的代码仅在到达字符串中的空格时才会执行。鉴于字符串末尾没有空格,它永远不会为最终单词执行。
  • 请包含正确的导入语句。如果我可以将它粘贴到调试器中并到达您所在的位置而无需调试导入,那么帮助您会容易得多。
  • 在学习编写程序的同时,学习编程工具同样重要。查看您的 IDE 的调试功能,并单步执行您的程序。观察你的变量,你肯定会发现事情在哪里搞砸了。
  • 您可以使用indexOf(' ')indexOf(' ', previousPosition + 1) 来查找单词分隔符并使用getChars 将其内容复制到一个字符数组中,而不是循环遍历所有字符并构建新字符串,只是为了给他们打电话toCharArray()

标签: java string algorithm sorting collections


【解决方案1】:

正如@sprinter 评论的那样:“将 sortedString 添加到单词的代码仅在您到达字符串中的空格时才会执行。鉴于字符串末尾没有空格,它永远不会为最终单词执行。”

解决此问题的一种方法是将您的 if 语句分解为处理空格的部分和处理单词的部分。:

for (int i=0; i < a.length; i++) {
    // if not space add to smallWords
    if (a[i] != ' ') {
        smallWords = smallWords + a[i];
    }
    // if space or last character, process smallWords
    if (a[i] == ' ' || i==a.length-1)  { 
        char sortedA[] = smallWords.toCharArray();
        Arrays.sort(sortedA);
        String sortedString = new String(sortedA);
        words.add(sortedString);
        smallWords = "";
    }
}

结果:

单词 :: [i, m, ervy, ervy, ahppy]
sortedWords :: [ahppy, ervy, i, m]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-14
    • 2017-06-07
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多