简体   繁体   中英

Java Create String From Byte Array Including Spaces

I ran into an issue when creating a String from a byte array where values of 0 inside the array are ignored when constructing the string. How can I make it so that if the byte value is 0, the String simply adds a space instead of removing it.

Example, the output of this is DT_TestTracelineCTestTraceli .

public static void main(String[] args) {
    byte[] text = {68, 84, 95, 84, 101, 115, 116, 84, 114, 97, 99, 101, 108, 105, 110, 101, 0, 0, 0, 0, 67, 84, 101, 115, 116, 84, 114, 97, 99, 101, 108, 105};
    System.out.println(new String(text));
}

How can I make it so I can separate those two strings using a tab character or uses spaces so the output is DT_TestTraceline CTestTraceli

Thanks

You should be specifying an encoding to new String() - Without one, you're using the platform default (which makes your code much less portable, as now you're making assumptions about the environment you're executing on).

Assuming you're using UTF-8, you can replace all of your zeroes with 32 , the UTF-8 code for the space character, and it should work:

for(int i = 0; i < text.length; i++) {
    if(text[i] == 0) {
        text[i] = 32; 
    }
}
String result = new String(text, StandardCharsets.UTF_8);

You can see it working on ideone .

一种方法是遍历数组,然后将其转换为字符串,并使用任何字符编码将“ 0”字符替换为空格的字符代码

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM