0

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. 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.

  • You can also simplify this process by using Regex expressions to extract all the digits. A good example can be found [here](https://stackoverflow.com/questions/4030928/extract-digits-from-a-string-in-java). – Tim Hunter Jul 14 '20 at 21:53

1 Answers1

1

Your process for walking through the array is fine, if you're not going to use 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. 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.')

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.

Zag
  • 638
  • 4
  • 8