2015-04-30 123 views
3

我是網絡編程的新手,之前從未使用過Java進行網絡編程。 我正在寫一個使用Java的服務器,並且我有一些來自客戶端的問題處理消息。我用java indexOf當它應該返回一個正數時返回-1

DataInputStream inputFromClient = new DataInputStream(socket.getInputStream()); 
while (true) { 
    // Receive radius from the client 
    byte[] r=new byte[256000]; 
    inputFromClient.read(r); 

    String Ffss =new String(r); 
    System.out.println("Received from client: " + Ffss); 
    System.out.print("Found Index :"); 

    System.out.println(Ffss.indexOf('\a')); 
    System.out.print("Found Index :"); 
    System.out.println(Ffss.indexOf(' ')); 

    String Str = new String("add 12341\n13243423"); 
    String SubStr1 = new String("\n");  
    System.out.print("Found Index :"); 
    System.out.println(Str.indexOf(SubStr1));  
} 

如果我這樣做,有一個樣品輸入ASG 23 \ AAG,它將返回:

Found Index :-1 
Found Index :3 
Found Index :9 

很明顯的是,如果String對象是從頭開始創建,的indexOf可以找到「\」。 如果從處理DataInputStream獲取字符串,代碼會如何定位\ a?

+2

無關,但不叫字符串對簡單的字符串創建構造函數。例如更喜歡'字符串foo =「foo」'在'字符串foo =新字符串(「foo」)' –

+0

@TheLostMind我沒有從我的編輯器複製代碼,這是一個錯字 – Armin

+0

@SteveKuo我犯了這個錯字,當我粘貼我的代碼後。對不起混淆 – Armin

回答

9

嘗試String abc=new String("\\a"); - 您需要\\在字符串中獲得反斜槓,否則\定義「轉義序列」的開始。

+0

解決了這個問題!謝謝 !! – Armin

+0

我可以問爲什麼它適用於String Str = new String(「add 12341 \ n13243423」)?當使用indexOf時,它不需要\\ n – Armin

+0

@Armin因爲在此字符串中\ n是新行的表示,請嘗試打印它,您將看到換行符。如果你想讓它自己打印一個\ n,你也需要在這裏轉義它。 – SomeJavaGuy

2

它看起來像a正在逃脫。

看看this article瞭解反斜槓如何影響字符串。

轉義序列

由反斜槓字符(\)是轉義序列 ,並具有特殊的意義給編譯器。下表 顯示了Java轉義序列:

| Escape Sequence | Description| 
|:----------------|------------:| 
| \t   | Insert a tab in the text at this point.| 
| \b   | Insert a backspace in the text at this point.| 
| \n   | Insert a newline in the text at this point.| 
| \r   | Insert a carriage return in the text at this point.| 
| \f   | Insert a formfeed in the text at this point.| 
| \'   | Insert a single quote character in the text at this point.| 
| \"   | Insert a double quote character in the text at this point.| 
| \\   | Insert a backslash character in the text at this point.| 
+0

這是一個有用的文件。謝謝! – Armin

相關問題