Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
70 views
in Technique[技术] by (71.8m points)

java - Converting char[][] to char[]

My goal is to print a new string like

char[] result = someArray();
System.out.print(new string(result))

I am working with 2 dimentional array in my task char[][]

I would like to convert my char[][] array to char[]

How do I either print a single string directly from char[][] or easily convert it to char[]?

Arrays.toDeepString() does not work for me as it prints in the format [[a,b,c],[d,e,f]] and I am looking for an output that is abcdef

question from:https://stackoverflow.com/questions/65891667/converting-char-to-char

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

2D arrays of chars can be easily converted into single string using String(char[]) constructor for each "row" array of chars followed by joining the resulting strings:

static String singleString(char[][] arr) {
    return Arrays.stream(arr)
                 .map(String::new)
                 .collect(Collectors.joining(""));
}

"Streamless" version using StringBuilder may look as follows:

static String singleString(char[][] arr) {
    StringBuilder sb = new StringBuilder(arr.length * (arr.length > 0 ? arr[0].length : 0));
    for (char[] row : arr) {
        sb.append(new String(row));
    }
    return sb.toString();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...