我是网络编程的新手,以前从未使用过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 12341n13243423");
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 时会出现问题?
尝试String abc=new String("\a");
- 你需要\
才能在字符串中获取反斜杠,否则定义了"转义序列"的开始。
看起来a
正在被转义。
请查看本文以了解反斜杠如何影响字符串。
转义序列
前面带有反斜杠 (\) 的字符是转义 序列,对编译器具有特殊意义。下表 显示了 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.|