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 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);
I can't think of a robust method that doesn't work as follows:
char[] data = new char[5];
data[0] = 'a';
data[1] = 'b';
data[2] = 'c';
StringBuilder builder = new StringBuilder();
for (char c : data) {
if (c != 0x00) {
builder.append(c);
}
}
System.out.println(builder.toString());
This specifically omits characters with a value equal to the default (0x00). Note, this is far from perfect as 0x00 is a legitimate char. I would suggest you re-evaluate the design decisions that lead you to this point.
I'm not a fan of the solutions that assume ((char) 0x00) is whitespace and can be trimmed. Even if it works. Note that:
System.out.println(' ' == ((char) 0x00));
will print false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With