从数组中删除重复的字符串

时间:2015-10-17 00:04:32

标签: java arrays string for-loop

我真的在努力解决这部分问题。我已经观看了几个小时的视频并在网上进行研究,但我似乎无法正确理解。我需要生成一个for循环,检查字符串是否为meg,删除它并移动剩余的元素。这不是一个arraylist。

  

写一个传统的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);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我们的想法是遍历数组的所有索引并检查它们是否等于"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]

答案 1 :(得分:0)

要按照您的指示操作,您可以尝试以下方法:

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]);
}
相关问题