157. 用 Read4 读取 N 个字符(仅java ac代码

 

 1 /**
 2  * The read4 API is defined in the parent class Reader4.
 3  *     int read4(char[] buf4);
 4  */
 5 
 6 public class Solution extends Reader4 {
 7     /**
 8      * @param buf Destination buffer
 9      * @param n   Number of characters to read
10      * @return    The number of actual characters read
11      */
12     public int read(char[] buf, int n) {
13         int ans = 0;
14         char[] buf4 = new char[4];//目标缓存区
15         int size = read4(buf4);
16         while(size>0&&ans<n){
17             //size>0指的是文件还有剩余的字符
18             //ans<n意思就是目前的长度不超过n
19             for(int i=0;i<size&&ans<n;++i){
20                 buf[ans++] = buf4[i];
21             }
22             size = read4(buf4);
23         }
24         return ans;
25     }
26 }

 

posted @ 2022-10-08 22:59  小草今天又在摸鱼吗  阅读(26)  评论(0编辑  收藏  举报