The following code, obviously, gives a rather weird result.
char[] data = new char[5];
data[0] = 'a';
data[1] = 'b';
data[2] = 'c';
out.println("'" + new String(data) + "'");
‘abc□□’
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
Stringhas constructorString(char[] value, int offset, int count) that accepts an array ofcharplus length (and offset):Assuming no embedded null characters (where a leading null character is considered to be an embedded null) in
datathe solution would need to locate the first null character to determine the number ofcharindata: