简体   繁体   English

如何删除字符数组中的“空白点”?

[英]How would I remove an “empty spot” in an array of characters?

I am just revising java.lang and I have a method where it looks for the integers in a string and it identifies them leaving out the non-integers.我只是在修改 java.lang 并且我有一个方法,它在字符串中查找整数并识别它们而忽略了非整数。 How would I then remove all of the remaining "empty slots" in the array.然后我将如何删除数组中所有剩余的“空槽”。 I don't know if the code will help but I am going to put it anyways.我不知道代码是否会有所帮助,但无论如何我都会把它说出来。

public static char[] lookForNums(@NotNull String str){
    char[] strPointer = str.toCharArray();
    char[] getNums = new char[str.length()];
    for(int i = 0; i < str.length(); i++){
        // point to X value in the array/string
        char pointer = strPointer[i];

        if(Character.isDigit(pointer)){
            getNums[i] = pointer;
        }
    }
    // Refinement/Garbage collection
    for(int i = 0; i < getNums.length; i++){
        if(getNums[i] == ' '){
            getNums[i] = 'n'; // n as null placeholder (for nothing)
        }
    }
    return getNums;
}// The challenge was I cant use String.charAt() or String.indexOf()

As you can see that garbage collection part pretty much is useless.如您所见,垃圾收集部分几乎没有用。 Thanks for reading.谢谢阅读。 I hope this is not a duplicate.我希望这不是重复的。

Your process for walking through the array is fine, if you're not going to use String.charAt().如果您不打算使用 String.charAt(),则遍历数组的过程很好。 (What you're doing is essentially the same, but if they're going to make silly restrictions, then use a technicality to get around them.) (您所做的基本上是相同的,但如果他们要做出愚蠢的限制,那么请使用技术来绕过它们。)

Rather than copying all the digits to their same spot in the new array and plan to clean up, you could copy them to the right spot in the new array.与其将所有数字复制到新数组中的同一位置并计划清理,不如将它们复制到新数组中的正确位置。 That is, don't use your index i in the new array, make a new index, start it at zero, and only increment it when you put a digit in the new array.也就是说,不要在新数组中使用你的索引 i,创建一个新索引,从零开始,并且只有在你将一个数字放入新数组时才增加它。 So the copy looks like所以副本看起来像

    if(Character.isDigit(pointer)){
        getNums[targetIndex++] = pointer;
    }

But then you'll want to copy it all to a new array that has the right size.但是你会想要将它全部复制到一个具有正确大小的新数组中。

(BTW, I hate that you're calling that 'pointer.' It isn't a pointer. Also, don't call your result getNums, that sounds like a method name. Call it 'result' or just 'nums.') (顺便说一句,我讨厌你调用那个'指针'。它不是一个指针。另外,不要调用你的结果getNums,这听起来像一个方法名称。称之为'result'或只是'nums'。 )

You could do the same thing by putting the isDigit characters into a new String with a StringBuilder, but since it looks like you want a char[] as a result, this way is fine, too.您可以通过使用 StringBuilder 将 isDigit 字符放入新字符串中来做同样的事情,但是由于看起来您想要一个 char[] 作为结果,所以这种方式也很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM