Java indexOf returns -1 when it should return a positive number
I am new to network programming and I have never used Java for network programming before. I am writing a server using Java and I have a message about a client problem. I used
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 ));
}
If I do this and you have asg 23 \ aag input sample, it returns:
Found Index :-1
Found Index :3
Found Index :9
It is clear that if a String object is created from scratch, indexOf can find "\". How is it that the code has a problem finding \ a if the String is obtained from processing a DataInputStream?
+3
source to share
2 answers
It looks like being escaped a
.
Check out this article to understand how a backslash affects a string.
Exit sequences
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The following table shows the Java escape sequences:
| 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.|
+2
source to share