首页 > 其他 > 详细

Output streams Convert to byte array

时间:2020-08-23 14:25:29      阅读:56      评论:0      收藏:0      [点我收藏+]

Imagine that we have a typing machine that accepts only one letter at a time for writing, but we want to write an array of words instead.

public class LetterPrinter {
    public void write(char letter) {
        //implementation
    }
}

To adapt an input to the LetterPrinter we need to write a converter from String[] to char[] and pass letters one by one to LetterPrinter instance:

public void writeWords(String[] words) throws IOException {
    LetterPrinter printer = new LetterPrinter();

    char[] letters = convert(words); // converting method
    for (char letter : letters) {
       printer.write(letter);
    }
}

Implement the convert method that converts String[] to char[].

Hint: use CharArrayWriter.

Example:
Input: ["This", " ", "is", " ", "a", " ", "test"]
Output: ["T", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "s", "t"]

import java.io.CharArrayWriter;
import java.io.IOException;

class Converter {
    public static char[] convert(String[] words) throws IOException {
        final var charArrayWriter = new CharArrayWriter();
        for (String word : words
             ) {
            charArrayWriter.write(word);
        }
        return  charArrayWriter.toCharArray();
    }
}

Output streams Convert to byte array

原文:https://www.cnblogs.com/longlong6296/p/13548924.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!