问题描述
以下code,很明显,给人一种相当怪异的结果。
的char []数据=新的char [5];
数据[0] ='A';
数据[1] ='B';
数据[2] ='c'的;通过out.println('+新的String(数据)+');
Is there a way to create a string from a character array which takes into account that the whole array might not be filled to the end with characters?
Reason for question: When using the Reader.read(char[])
method you give it a character array to fill, which I can only assume won't be fully filled, unless you're lucky, when you reach the end of the stream. So was wondering how you could turn this into a string you could append to a StringBuffer
. Realize now though that the read
method actually returns the number of bytes read though, which I assume can be used in combination with StringBuffer.append(char[], int, int)
, which renders my question moot. But, still something I am curious about and not something I managed to find by googling, so I guess this question is good to have an answer for here ;)
The String
has constructorString(char[] value, int offset, int count) that accepts an array of char
plus length (and offset):
String s = new String(data, 0, 3);
Assuming no embedded null characters (where a leading null character is considered to be an embedded null) in data
the solution would need to locate the first null character to determine the number of char
in data
:
int length = 0;
while (length < data.length && 0 != data[length]) length++;
String s = new String(data, 0, length);
这篇关于从没有完全填补字符数组的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!