简体   繁体   English

无法将通过蓝牙接收的字符串与普通字符串进行比较

[英]Can't compare string received through Bluetooth with normal String

I have a connection between Arduino and Android phone. 我在Arduino和Android手机之间建立了连接。

This is the string that I'm receiving: always the string 555 , I know because I tested it: 这是我正在接收的字符串:始终是字符串555 ,我知道是因为我测试了它:

    final String data = new String(encodedBytes, "US-ASCII");
    String toCompare = data;

But this will always print false : 但这总是打印false

txtArduino.setText(String.valueOf(toCompare.equals("555")));

I think that the format is different or something like that, because I know for sure that I'm receiving 555 . 我认为格式是不同的或类似的东西,因为我确定我会收到555

53 53 53 13 in ASCII is 5 5 5 ␍ 53 53 53 13 ASCII为5 5 5␍

new String converts that to Unicode/UTF-16, which as a literal in Java would be "555\\r" or "555\ ". new String将其转换为Unicode / UTF-16,在Java中,原义为“ 555 \\ r”或“ 555 \\ u000D”。 So, you should compare to that. 因此,您应该对此进行比较。

final String data = new String(encodedBytes, "US-ASCII");
String toCompare = data;

txtArduino.setText(String.valueOf(toCompare.equals("555\r")));

Depending on your Bluetooth library, you might have to consider that you are receiving a stream of bytes and that each read gives you all available bytes. 根据您的蓝牙库,您可能必须考虑正在接收字节 ,并且每次读取都会为您提供所有可用字节。 It would then be up to you to split the stream into messages. 然后由您决定将流分成消息。 This could be the purpose of the ␍. 这可能是␍的目的。

Your input string includes the newline at the end. 输入字符串的末尾包含换行符。 Trim it. 修剪一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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