2012-12-13 19 views
9

Come sostituire \ 0 (NUL) nella stringa?Caratteri speciali 0 {NUL} in Java

String b = "2012yyyy06mm";    // sth what i want 
String c = "2\0\0\0012yyyy06mm"; 
String d = c.replaceAll("\\\\0", ""); // not work 
String e = d.replace("\0", "");   // er, the same 
System.out.println(c+"\n"+d+"\n"+e); 

String bb = "2012yyyy06mm"; 
System.out.println(b.length() + " > " +bb.length()); 

Il codice precedente stamperà 12> 11 in console. Oops, cosa è successo?

String e = c.replace("\0", ""); 
System.out.println(e);  // just print 2(a bad character)2yyyy06mm 

risposta

14

La stringa "2\0\0\0012yyyy06mm" non inizia 2 {NUL} {NUL} {NUL} 0 1 2, ma invece contiene 2 {NUL} {NUL} {SOH} 2.

Il \001 viene trattata come un singolo carattere ASCII 1 (SOH) e non come NUL seguita da 1 2.

Il risultato è che vengono rimossi solo due caratteri, non tre.

Non credo che ci sia alcun modo per rappresentare le cifre a seguito di un abbreviato octal escape diverso rompendo la stringa a parte:

String c = "2" + "\0\0\0" + "012yyyy06mm"; 

o in alternativa, specificare tutte e tre le cifre del (ultimo) ottale sfuggire tale che le seguenti cifre non vengono interpretati come facenti parte della fuga ottale:

String c = "2\000\000\000012yyyy06mm"; 

Una volta fatto questo, la sostituzione "\0" secondo la vostra linea:

String e = c.replace("\0", ""); 

funzionerà correttamente.

+0

Ciao, tls per aiuto. Stringa c = "2 \ 0 \ 0 \ 0012aaaa06mm"; \t \t Stringa e = c.replace ("\ 0", ""); \t \t System.out.println (e); \t \t \t \t // stampa solo 22yyyy06mm – user1900556

+1

@ user1900556 sì, perché il '\ 001' ancora incorporato in esso (tra i due" 2 ") è invisibile. Il punto è che la stringa 'c' che hai non contiene ciò che pensi che faccia. – Alnitak

+0

Non c'è modo? In quale altro modo può essere fatto? – user1900556