删除数组中某个位置的字符

时间:2013-09-20 05:41:16

标签: java arrays

我要做的是删除数组中某个位置的字符。该数组称为word。

removecharacter是一个int

word是一个由字符串

组成的数组

已经编写了一个测试程序,其中人可以输入一个int(removecharacter),它将给出数组中删除项目的位置

我认为我在正确的轨道上,但我不确定某条线,这是实际的删除线。有什么提示吗?

public boolean delCharAt(int removecharacter) {
    if (removecharacter <= word.length && delete >= 0) 
    {

        //I wish to delete the character at removecharacter

    }

有关从何处出发的任何帮助?感谢

4 个答案:

答案 0 :(得分:4)

如果删除数组中的元素,则应考虑使用(数组)列表。您将有一个方法从列表中删除对象或索引中的元素。尽量避免重新发明轮子。

这是Javadoc:http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

另外,因为你的单词来自一个字符串,你可以使用StringBuilder,你有一个名为deleteCharAt的方法。

答案 1 :(得分:1)

如果您想要添加和删除的多功能性,您可以考虑使用ArrayList或List。他们都有内置的功能来完成这项任务。

如果你绝对必须使用数组,你还必须存储我使用的数组长度的值。

答案 2 :(得分:0)

完成此任务的一种方法是在删除的值之后向下移动所有值。然后,您可以将新的空槽设置为null。

if(removecharacter <= word.length && removecharacter >= 0)
{
    for(int i=removecharacter+1; i<word.length; i++) {
         word[i-1] = word[i];
         word[i] = '\u0000'; // This will make sure that no duplicates are created in this                     
                             // process.
    }
}

答案 3 :(得分:0)

我和其他所有使用ArrayList之类的人在一起,但是如果你别无选择,你可以使用System.arraycopy将原始数组中的内容复制到新的数组中,临时数组并将结果分配回原始数据(word)。

这将减少数组的大小并删除字符...

public class ArrayDelete {

    // This is because I'm to lazy to build the character
    // array by hand myself...
    private static String text = "This is an example of text";
    private static char word[] = text.toCharArray();

    public static void main(String[] args) {
        System.out.println(new String(word));
        delete(9);
        System.out.println(new String(word));
    }

    public static void delete(int charAt) {
        if (word.length > 0 && charAt >= 0 && charAt < word.length) {
            char[] fix = new char[word.length - 1];

            System.arraycopy(word, 0, fix, 0, charAt);
            System.arraycopy(word, charAt + 1, fix, charAt, word.length - charAt - 1);

            word = fix;
        }
    }

}

此示例输出......

This is an example of text
This is a example of text