我正在将字符串解析为由字符的第一次出现划分的 2 个部分'&'
。例如:如果字符串是555&hello &world
,则分区将是555
和hello &world
。我使用了以下代码:
String[] numberAndMessage=currentMessage.split("(\\&)",2);
System.out.println(numberAndMessage[1]+storedMessage.message+"end");
因此,输入:555&hello &world
我期望的输出是:hello &worldend
但相反,它给出了:hello &world
第二分区的结尾字符可能有任何问题。但问题是什么?
编码:
UDPServer.java:
import java.net.*;
public class UDPServer extends Thread{
public void run(){
try{
DatagramSocket serverSocket = new DatagramSocket(9999);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String currentMessage = new String( receivePacket.getData());
System.out.println("RECEIVED: " + currentMessage);
String[] numberAndMessage=currentMessage.split("(\\&)", 2);
System.out.println("noAndMessage[0]="+numberAndMessage[0]+";noAndMessage[1]="+numberAndMessage[1]);
System.out.println("numberAndMessage[1]= "+numberAndMessage[1]+"end");
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception
{
UDPServer server=new UDPServer();
server.start();
}
}
UDPClient.java:
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9999);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
在 UDPClient.java 处输入:
555&hello world
UDPServer.java 的输出:
RECEIVED: 555&hello world
noAndMessage[0]=555;noAndMessage[1]=hello world
numberAndMessage[1]= hello world