2

I have an array String ar[] = {"HalloWelt", " "};, ar.length is 2.

It does register two values within "HalloWelt" on index 0, and a blank/empty string on index 1;

I wonder how can I remove empty space on the index 1 - > but also keep it as a String Array since it is necessary for next task. Or how to do bunch of conversions but end up with String Array in the end.

My attempt

public String[] arraysWhiteSpaceEliminator(String[] arr) {

        int k=0;   //Identify how big the array should be i.e. till it reaches an empty index.

        for(int i=0; i<bsp.length;i++) {
            arr[i].trim();
            System.out.println(arr[i].isEmpty());
            if(arr[i].isEmpty()) {
            }
            else {
                k = k+1; //if the index isn't empty ==  +1;
            }

        }

        String[] clearnArray = new String[k];
        for(int s = 0; s<k; s++) {
            clearnArray [s] = arr[s];  //define New Array till we reach the empty index.
            //System.out.println(clearnArray [s]+" " +s); 
        }

        return clearnArray ;

    };

The logic is very simple:

  1. Identify how big the clearnArray should be.
  2. Iterate through original Array with .trim() to remove white Space and check wether isEmpty().
  3. Add to the k if the index isnt Empty.
  4. Create clearnArray with the k as size.
  5. Loop through originial Array till k -> add all the items to cleanArray till k.

Issue: .trim() and .isEmpty() don't record that the index is empty. ?!

  • this `String ar[] = ["HalloWelt",];` is not valid. How is your array initialized? – jhamon Jan 14 '20 at 14:24
  • 1
    Does this answer your question? [Resize an Array while keeping current elements in Java?](https://stackoverflow.com/questions/13197702/resize-an-array-while-keeping-current-elements-in-java) – jhamon Jan 14 '20 at 14:26
  • String content = new String(Files.readAllBytes(path), Charset.defaultCharset()); String [] data = content.split(",\\R"); content -> reads from a File information blocks. This Blocks are usually divded by "," the last one too eventho after the last one there isn't any Information - > those this is where white space comes from. –  Jan 14 '20 at 14:31
  • it's unclear if you want to (a) resize the array to exclude the blank string, (b) turn the white-space string to an empty string, (c) turn the white-space string to null – jhamon Jan 14 '20 at 14:42
  • Does this answer your question? [In Java, remove empty elements from a list of Strings](https://stackoverflow.com/questions/5520693/in-java-remove-empty-elements-from-a-list-of-strings) – Noa Jan 14 '20 at 14:51
  • My Goal is to remove every single blank String within an String Array, so there are only non-blank values such as "HelloWorld" etc.. Partly... –  Jan 14 '20 at 18:33

4 Answers4

1

A solution with streams:

String[] clean = Arrays.stream(ar)
    .map(String::trim)
    .filter(Predicate.isEqual("").negate())
    .toArray(String[]::new);

Note that this assumes none of the array elements are null. If this is a possibility, simply add the following stage before the map:

.filter(Objects::nonNull)
SDJ
  • 4,083
  • 1
  • 17
  • 35
0

in your method, create a new

List cleanedList = new ArrayList();

add iterate through ar[]ar[] = ["HalloWelt",""], and add only non-empty values to cleaned List....then return the array.

return cleanedList.toArray()

like below:

List<String> cleanedList = new ArrayList<>();

for(String s : arr) {
    s = s.trim();
    if(!s.isEmpty()) {
        cleanedList.add(s);
    }
}

return cleanArray.toArray();
Jeryl Cook
  • 989
  • 17
  • 40
0

The problem with your code is that after counting to find k, you just write the first k elements from the original array. To solve the problem by your technique, you need to check each element of the input array again to see if it's empty (after trimming), and only write to the new array the elements which pass the test.

The code can be simplified using the "enhanced" for loop, since you don't need indices for the original array. (The variable i keeps track of the current index in the new array.) Note also that strings are immutable, so calling .trim() does nothing if you don't use the result anywhere. Your code also refers to bsp which is not defined, so I changed that.

int k = 0;

for(String s : arr) {
    s = s.trim();
    if(!s.isEmpty()) {
        k++;
    }
}

String[] cleanArray = new String[k];
int i = 0;
for(String s : arr) {
    s = s.trim();
    if(!s.isEmpty()) {
        cleanArray[i] = s;
        i++;
    }
}

return cleanArray;
kaya3
  • 47,440
  • 4
  • 68
  • 97
0

Calculate the number of non-null elements and create an array of that size, like

String[] strs = ...;
int count = 0;
for (int i = 0; i < strs.length; i++) {
  if (strs[i] != null) count++;
}
String newStrArray[] = new String[count];
int idx = 0;
for (int i = 0; i < strs.length; i++) {
  if (strs[i] != null) newStrArray[idx++] = strs[i];
}
return newStrArray;

You could also probably make this prettier using streams. However I haven't used streaming functionality in Java, so I can't help there.

Two things to note:

  1. Unless you are serializing or the nulls are causing other problems, trimming the array just to get rid of the nulls probably won't have an impact on memory, as the size of an array entry (4 bytes) is very likely inconsequential to the memory block size allocated for the Array object

  2. Converting first to an List and then back to an array is lazy and possibly inefficient. ArrayList, for example, will likely include extra space in the array it creates internally so that you can add more elements to the ArrayList and not have to create a whole new internal array.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80