【问题标题】:java indexOf returns -1 when it's supposed to return a positive number当它应该返回一个正数时,java indexOf 返回 -1
【发布时间】:2015-07-09 16:04:43
【问题描述】:

我是网络编程的新手,以前从未使用 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可以定位到“\”。 如果 String 是从处理 DataInputStream 中获得的,那么代码如何定位 \a 会有问题?

【问题讨论】:

  • 不相关,但不要调用String的构造函数进行简单的字符串创建。例如更喜欢String foo = "foo" 而不是String foo = new String("foo")
  • @TheLostMind 我没有从我的编辑器复制代码,这是一个错字
  • @SteveKuo 我打错字了,我在粘贴代码后做了一些改动。很抱歉造成混乱

标签: java network-programming substring indexof datainputstream


【解决方案1】:

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

【讨论】:

  • 请问为什么它适用于 String Str = new String("add 12341\n13243423")?使用 indexOf 时不需要 \\n
  • @Armin 因为在这个字符串中这个 \n 是一个新行的表示,尝试打印它,你会看到一个换行符。如果你想让它自己打印一个\n,你还需要在这里转义它。
【解决方案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.|

【讨论】:

    猜你喜欢
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 2016-03-18
    • 2016-01-14
    • 1970-01-01
    相关资源
    最近更新 更多