简体   繁体   中英

Java: How to convert String of ASCII to String of characters?

I am sending a message from one device to another using MQTT client/broker. The message is exchanged (sent and received) between the two devices as String succesfully.

However, on the MQTT-Broker (ie: the server) the message characters are received as ASCII numbers within a string.

For example if I send:

"This is a test"

On the broker it show:

"84,104,105,115,32,105,115,32,97,32,116,101,115,116,10"

Using Java, I need a way to convert this string of ASCII back to string on the server for further process.

How to do that ? thanks

您可以使用带分隔符的逗号分隔符StringTokenizer来中断字符串,然后在每个字符串上进行迭代并使用Character.toString((char)i);

Convert the string to a byte[] and create a new string using the byte[]

String str = "84,104,105,115,32,105,115,32,97,32,116,101,115,116,10";
String[] chars = str.split(",");
byte[] bytes = new byte[chars.length];
for (int i = 0; i < chars.length; i++) {
  bytes[i] = Byte.parseByte(chars[i]);
}
return new String(bytes);

You can use stream as well for this, if you can use java-8

String str = Stream.of("84,104,105,115,32,105,115,32,97,32,116,101,115,116,10".split(","))
        .map(ch -> (char) Integer.valueOf(ch).intValue())
        .collect(StringBuilder::new,
                StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
System.out.println(str); // This is a test

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