当它应该返回正数

时间:2015-04-30 05:13:57

标签: java network-programming substring indexof datainputstream

我是网络编程的新手,之前从未使用过Java进行网络编程。 我正在使用Java编写服务器,我从客户端处理消息时遇到了一些问题。我用了

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获得String,代码如何定位问题?

2 个答案:

答案 0 :(得分:9)

尝试String abc=new String("\\a"); - 您需要\\才能在字符串中获得反斜杠,否则\会定义“转义序列”的开头。

答案 1 :(得分: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.|