I get a string in the byte array from the socket that looks like this:
[128,5,6,3,45,0,0,0,0,0]
The size specified by the network protocol is the total length of the string (including zeros), so in my example 10.
If I just do:
String myString = new String(myBuffer);
I have the wrong character at the end of line 5. The conversion does not seem to detect the end of the string character (0).
To get the correct size and the correct string, I do this:
int sizeLabelTmp = 0; //Iterate over the 10 bit to get the real size of the string for(int j = 0; j<(sizeLabel); j++) { byte charac = datasRec[j]; if(charac == 0) break; sizeLabelTmp ++; } // Create a temp byte array to make a correct conversion byte[] label = new byte[sizeLabelTmp]; for(int j = 0; j<(sizeLabelTmp); j++) { label[j] = datasRec[j]; } String myString = new String(label);
Is there a better way to deal with the problem?
thank
0 " ". . , , , ( ). , UTF-16, 0 ASCII.
, 0 , - , , :
int size = 0; while (size < data.length) { if (data[size] == 0) { break; } size++; } // Specify the appropriate encoding as the last argument String myString = new String(data, 0, size, "UTF-8");
- ββ Unicode. - , , , .
, , , , . , ( " " ), , - .
, , . , , new String(myBuffer).trim(), , .
new String(myBuffer).trim()
Java 0, . 0 , . , , 0, String ( , 0 ), String trim(). , ASCII 32 .
trim()
, , . StringBuilder , , .
, . , String. , :
byte[] foo = {28,6,3,45,0,0,0,0}; int i = foo.length - 1; while (foo[i] == 0) { i--; } byte[] bar = Arrays.copyOf(foo, i+1); String myString = new String(bar, "UTF-8"); System.out.println(myString.length());
4.
, , read(). , , , , , .
int count = in.read(buffer); if (count < 0) ; // EOS: close the socket etc else String s = new String(buffer, 0, count);
, OP, ?
public static String bytesToString(byte[] data) { String dataOut = ""; for (int i = 0; i < data.length; i++) { if (data[i] != 0x00) dataOut += (char)data[i]; } return dataOut; }