从字符串数组中删除元素后,如何减少元素的索引? [英] How can you reduce the indices of elements in a string array after deleting an element from it?

查看:64
本文介绍了从字符串数组中删除元素后,如何减少元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务,创建一个采用字符串数组元素的方法,检查是否存在重复项,然后将其删除(我尝试用"null"进行的操作),然后将所有其他元素移向索引值[0]来缩小差距.

I've got a task, to create a method that takes the elements of a string array, checks if there's a duplicate, then deletes it ( what I tried with "null") and then moves all the other elements towards index value [0] to close the gap(s).

现在看起来像这样:

public static boolean deleteTask() {
    boolean removed = false;
    for (int pos = 0; pos < todos.length; pos++) {
        if (todos[pos].equals(titel)) {
            todos[pos] = null;
            removed = true;
   
            if (removed){
                //set pos+1 = pos to reduce each value -1. 
                //repeat process for each index [10]
                }
            }
        }
        return removed;
    }
}

在图片中,我显示了看到的结果.例如.pos.4是重复的-然后将其设置为null.现在,以下所有索引必须更改为-1才能填补空白.显然,然后将索引设置回456而不是567,这只是为了说明字符串的移动.

In the picture I've shown what I see the result like. E.g. pos.4 was a duplicate - it was then set to null. Now all the following indexes have to be changed to -1 to fill the gap. Obviously the index is then set back to 456 instead of 567 this is just to illustrate the movement of the string.

在[pos]为null之后,您能帮我在-1方向上移动索引吗?

Can you help me move the indexes in -1 direction after [pos] null ?

如果您可以帮助2次以上重复做同样的事情,那将会更大.

If you could help with doing the same for 2+ duplicates, that would be even greater.

推荐答案

代替

todos[pos + 1] = todos[pos];

您应该使用

todos[pos] = todos[pos + 1];

这是工作代码:

public static boolean deleteTask() {
    boolean removed = false;
    for (int pos = 0; pos < todos.length; pos++) {
        if (todos[pos].equals(titel)) {
            todos[pos] = null;
            removed = true;
        }
        if (removed && pos < todos.length - 1) {
            // swap the string with the next one
            // you can't do this with the last
            // element because [pos + 1] will
            // throw an indexoutofbounds exception
            todos[pos] = todos[pos + 1];
        } else if (removed && pos == todos.length - 1) {
            // here you can swap the last one with null
            todos[pos] = null;
        }
    }
    return removed;
}

这篇关于从字符串数组中删除元素后,如何减少元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆