简体   繁体   中英

Java Substring always evaluates to false

I am trying to parse a string but first I need to check that "@\\n" is the first thing in the string. I've verified that I am getting the correct data using the .substring(start,end) method but when I try to evaluate that substring using either the contains() or equals() it always returns false.

Log.v("DLI",data.substring(0,3));
    Log.v("DLI","Contains:"+data.substring(0,3).contains("@\n"));
    Log.v("DLI","Equals:"+data.substring(0,3).equals("@\n"));

Below is the Log out put:

12-18 05:28:51.899  21610-21610/? V/DLI﹕ @\n
12-18 05:28:51.899  21610-21610/? V/DLI﹕ Contains:false
12-18 05:28:51.899  21610-21610/? V/DLI﹕ Equals:false

And this is the String that I am trying to parse (Android Studio escaped it when I pasted it in, so i've included the AS version(First) and the original version(Second)

"@\\n\\x1e\\rANSI 6360200102DL00390187ZV02260031DLDAQ0123456789ABC\\nDAAJOHN,Q,PUBLIC\\nDAG123 MAIN STREET\\nDAIANYTOWN\\nDAJVA\\nDAK123459999  \\nDARDM  \\nDAS          \\nDAT     \\nDAU509\\nDAW175\\nDAYBL \\nDAZBR \\nDBA20011201\\nDBB19761123\\nDBCM\\nDBD19961201\\rZVZVAJURISDICTIONDEFINEDELEMENT\\r"

"@\n\x1e\rANSI 6360200102DL00390187ZV02260031DLDAQ0123456789ABC\nDAAJOHN,Q,PUBLIC\nDAG123 MAIN STREET\nDAIANYTOWN\nDAJVA\nDAK123459999  \nDARDM  \nDAS          \nDAT     \nDAU509\nDAW175\nDAYBL \nDAZBR \nDBA20011201\nDBB19761123\nDBCM\nDBD19961201\rZVZVAJURISDICTIONDEFINEDELEMENT\r"

Special Strings in JAVA: ( http://www.freeformatter.com/java-dotnet-escape.html )

  • Backspace is replaced with \\b
  • Newline is replaced with \\n
  • Tab is replaced with \\t
  • Carriage return is replaced with \\r
  • Form feed is replaced with \\f
  • Double quote is replaced with \\"
  • Backslash is replaced with \\\\

Note that for back slash you have to give two back slashes "\\".

so use two back slashes ("\\\\") while comparing.

data.substring(0,3).contains("@\\n")

escape sequence

data.substring(0,3).contains("@\\n")

instead of

data.substring(0,3).contains("@\n")

请勿使用字符,而是在子字符串的参数中使用index,

substring(0,3);

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