【问题标题】:Removing Duplicate String from array从数组中删除重复的字符串
【发布时间】:2015-10-17 00:04:32
【问题描述】:

我真的在这部分问题上苦苦挣扎。我已经看了好几个小时的视频并在网上进行了研究,但我似乎无法正确理解。我需要生成一个 for 循环来检查 meg 的字符串,删除它并移动剩余的元素。这不是一个数组列表。

编写第二个传统的 for 循环来检查每个 字符串的元素“ 梅格 ”,如果在 数组,删除它,移动剩余元素,并显示名称数组。

我知道我的 for 循环会在我的最后一个客户名称和用于打印它的 for 之间进行。我只是不知道下一步该做什么。

这是我当前的代码:

public class CustomerListerArray {
    public static void main(String[] args) {
        String customerName[] = new String[7];
        customerName[0] = "Chris";
        customerName[1] = "Lois";
        customerName[2] = "Meg";
        customerName[3] = "Peter";
        customerName[4] = "Stewie";
        for (int i = customerName.length - 1; i > 3; i--) {
            customerName[i] = customerName[i - 2];
        }
        customerName[3] = "Meg";
        customerName[4] = "Brian";
        for (String name: customerName) {
            System.out.println(name);
        }
    }
}

【问题讨论】:

    标签: java arrays string for-loop


    【解决方案1】:

    要按照您收到的说明进行操作,您可以尝试以下操作:

    int max = customerName.length;
    for (int i = 0; i < max; i++) {   // Traditional for loop
        if ("Meg".equals(customerName[i]) {    // Look for the name "Meg"
            // If found, shift the array elements down one.
            for (int j = i; j < (max - 1); j++) {
                customerName[j] = customerName[j+1];
            }
            i--;  // Check the i'th element again in case we just move "Meg" there.
            max--; // Reduce the size of our search of the array.
        }
    }
    

    完成后,您可以遍历结果并打印数组:

    for (int i = 0; i < max; i++) {
        System.out.println(customerName[i]);
    }
    

    【讨论】:

    • @sam2090 关于不区分大小写的搜索的问题中没有任何内容,但如果需要,当然可以这样做。
    • @dave 非常感谢您的帮助。由于某些奇怪的原因,这会删除第一个 Meg 而不是第二个。
    • @BlueJay 看起来好像有一个错误 :) 如果“Meg”出现在连续的元素中,我会说它被破坏了。我想我已经解决了。
    • @3kings 我想我都需要。第一个处理我们正在搜索的单词的连续实例。第二个是阻止我们搜索现在为空的元素,因为我们移动了它们。
    • 你太棒了@dave
    【解决方案2】:

    这个想法是遍历数组的所有索引并检查它们是否等于"Meg"。如果不是这种情况,则将索引的值连接到StringBuilder 对象。

    最后,我们获取 StringBuilder 对象字符串的值,并用我们在名称之间放置的额外空格将其拆分。

    我们终于有了想要大小的新String 数组。

    public static void main(String[] args) {
        String customerName[] = new String[7];
        customerName[0] = "Chris";
        customerName[1] = "Lois";
        customerName[2] = "Meg";
        customerName[3] = "Peter";
        customerName[4] = "Stewie";
        customerName[5] = "Meg";
        customerName[6] = "Brian";
        StringBuilder names = new StringBuilder();
        for (String name: customerName) {
            if (!name.equals("Meg")) names.append(name + " ");
        }
        String[] myNewArray = names.toString().split(" ");
        System.out.println(Arrays.toString(myNewArray));
    }
    

    输出:

    [Chris, Lois, Peter, Stewie, Brian]
    

    【讨论】:

    • @sam2090 No => "字符串“Meg”的每个元素"
    猜你喜欢
    • 1970-01-01
    • 2018-06-09
    • 2012-05-09
    • 2012-09-15
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多