How to determine the end of a string in a byte array for string conversion?

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

+5
source share
6 answers

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. - , , , .

, , , , . , ( " " ), , - .

+7

, , . , , new String(myBuffer).trim(), , .

+9

Java 0, . 0 , . , , 0, String ( , 0 ), String trim(). , ASCII 32 .

, , . StringBuilder , , .

+2

, . , 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.

+2

, , read(). , , , , , .

int count = in.read(buffer);
if (count < 0)
  ; // EOS: close the socket etc
else
  String s = new String(buffer, 0, count);
+1

, 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;
}
+1

All Articles