从没有完全填补字符数组的字符串 [英] String from not fully filled character array
问题描述
以下code,很明显,给人一种相当怪异的结果。
的char []数据=新的char [5];
数据[0] ='A';
数据[1] ='B';
数据[2] ='c'的;通过out.println('+新的String(数据)+');
ABC□□
块引用>有没有一种方法来创建一个字符数组,考虑到整个阵列可能不填充与字符结尾的字符串?
原因问题:使用的
Reader.read(的char [])
方法,你给它一个字符数组来填充,这我只能假设不会被填满,除非你是幸运的,当你到达流的末尾。所以,想知道你怎么可以变成一个字符串,这个你可以追加到的StringBuffer
。现在意识到,虽然该读
方法实际上返回的字节数读虽然,我以为可以结合使用的StringBuffer.append(的char [ ],INT,INT)
,这使得我的问题没有实际意义。但是,仍然是我很好奇,这也不是我设法使用Google找到,所以我想这个问题是好事,有一个答案在这里;)解决方案的
字符串
具有构造<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#String%28char%5b%5d,%20int,%20int%29\"相对=nofollow>字符串(的char []的价值,诠释抵消,诠释计数)接受字符
加长度(和偏移):一个String =新的String(数据,0,3);
假设没有嵌入空字符(其中一个领先的空字符被认为是一个嵌入的NULL)的
数据
的解决方案将需要找到第一个空字符确定字符
在数据
号:INT长度= 0;
而(长度LT; data.length&放大器;&安培;!0 =数据[长度])长度++;
字符串s =新的String(数据,0,长度);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 aStringBuffer
. Realize now though that theread
method actually returns the number of bytes read though, which I assume can be used in combination withStringBuffer.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 ofchar
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 ofchar
indata
:int length = 0; while (length < data.length && 0 != data[length]) length++; String s = new String(data, 0, length);
这篇关于从没有完全填补字符数组的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!