Removing all empty elements from an character array

后端 未结 5 2003
面向向阳花
面向向阳花 2021-01-15 11:07

I have a character array that can hold maximum 50000 characters at a time. Contents of this array are coming through socket connections. However it is not guaranteed that th

相关标签:
5条回答
  • 2021-01-15 11:35

    use an array list instead! This wil allow you to remove array elements, whereas the standard array package has no 'easy' way of doing this.

    ArrayList buffer = new ArrayList (50000)

    buffer.add(x)

    buffer.remove(x)

    http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

    Note: instantiate a type on the ArrayList

    0 讨论(0)
  • 2021-01-15 11:47

    I would suggest converting the array to a string and using the replaceAll and trim functions to remove the empty elements.

    String bufferString = new String(buffer).trim().replaceAll(" ", "");
    

    This does not require any additional libraries.

    0 讨论(0)
  • 2021-01-15 11:54
    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, encoding);
    String theString = writer.toString();
    

    OR

    String theString = IOUtils.toString(inputStream, "UTF-8");
    
    0 讨论(0)
  • 2021-01-15 11:57

    something like that should work too :

    public String readBufferUpdate() throws IOException {
      char[] buffer =new char[50000];
      is.read(buffer);
    
      return new String(ArrayUtils.removeElements(buffer, ''));
    }
    

    Doc here : http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#removeElements(char[], char...)

    0 讨论(0)
  • 2021-01-15 11:58

    Correct way to read from an InputStream in a buffer is as follows.

    public String readBufferUpdate() throws IOException {
        char[] buffer =new char[50000];
        int bytesRead = is.read(buffer, 0, buffer.length);
        return new String(buffer, 0, bytesRead);
    }
    

    Here you is.read() returns how many bytes have been read into bytesRead. Only that many bytes are copied from the buffer to String.

    0 讨论(0)
提交回复
热议问题