Read N Characters Given Read4 II - Call multiple times

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Keep two global various hasReadLen and buffStr, which record the read data length and buffer.

Read buf as Problem 1, but keep the char into buffStr, and each time read next char from buffStr when index < n and index + hasReadLen < buffStr.length

/* The read4 API is defined in the parent class Reader4.
      int read4(char[] buf); */

public class Solution extends Reader4 {
    /**
     * @param buf Destination buffer
     * @param n   Maximum number of characters to read
     * @return    The number of characters read
     */

    private int hasReadLen = 0;

    private String buffStr = "";

    public int read(char[] buf, int n) {

        int idx = 0;
        boolean eof = false;

        while(idx < n){

            char [] tmp = new char[4];

            if(eof) break;

            if(read4(tmp) == 0) eof = true;

            for(char c : tmp){
                if(c != 0x00)
                    buffStr += String.valueOf(c);
            }

            while(idx < n && idx + hasReadLen < buffStr.length()){
                buf[idx] = buffStr.charAt(idx + hasReadLen);
                idx ++;
            }

        }

        hasReadLen += idx;

        return idx;
    }
}

results matching ""

    No results matching ""