namenotfound
namenotfound

Reputation: 83

removing all spaces from a char array. can't figure out how to make it work

  if (x[i] != 32)                 
            {

            y[i] = x[i];
           }

this is part of a loop which repeatedly runs through every char in the x array and if it is not a space puts it in they y array. but they y array winds up with spaces anyway. which means this if statement is being executed regardless of weather the char in question is a ' ' char or not. how do I make this if statement actually work?

Upvotes: 0

Views: 43

Answers (4)

PBHound
PBHound

Reputation: 11

Looks like you're skipping indices. If you're at index 2 in array 1, then you'll place the char at index 2 in array 2--leaving a space from where you previously didn't post a character.

To make this work you might want to track the index:

if (x[i] != 32) { y[i] = x[index]; index ++; }

Upvotes: 1

Marcelo Keiti
Marcelo Keiti

Reputation: 1240

The problem is not in the comparison. I suppose you are running a code like this:

    char[] x = new char[]{'a','b',' ','c'};
    char[] y = new char[4];
    for (int j = 0; j < x.length; j++) {
        if (x[j] != 32) {
            y[j] = x[j];
        }
    }
    for (int i = 0; i < y.length; i++) {
        System.out.println(y[i]);
    }

The char array is initialized with \u0000 which prints empty character. So even if the comparison fails it will keep initial char value in that position.

Try to run the following code and you will see that the comparison fails:

char[] x = new char[]{'a','b',' ','c'};
char[] y = new char[4];
for (int j = 0; j < x.length; j++) {
  if (x[j] != 32) {
    System.out.print(x[j] + ", ");
  }
}

result: a, b, c,

Upvotes: 0

guido
guido

Reputation: 19194

Because you use the same index 'i' for both arrays, you are leaving an 'hole' in the 'y' array for any found space:

if (x[i] != ' ') {
    y[i] = x[i];
}

Use two different indexes (but be aware that 'y' which I guess has been initialized to 'i length', will have holes at the end), something like:

int i = 0;
int j = 0;
while (i .... {
    if (x[i] != ' ') {
        y[j++] = x[i];
    }
    ...
}

Upvotes: 1

Zielu
Zielu

Reputation: 8552

I don't know if space code is actully 32 but nevertheless you walk y array with the same index as x, so it copies the characters to the same positon leaving gaps (0) between.

Upvotes: 0

Related Questions