gpt4 book ai didi

java indexOf 在应该返回正数时返回 -1

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:38:20 24 4
gpt4 key购买 nike

我是网络编程的新手,以前从未使用过 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 abc=new String("\\a"); - 你需要 \\ 来得到字符串中的反斜杠,否则 \ 定义“转义序列”的开始。

关于java indexOf 在应该返回正数时返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29959505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com