如何使用Java在TCP中反转字符串中的顺序?

时间:2014-06-21 18:40:16

标签: java

我写过TCPClient.java和TCPServer.java。 TCPServer将简单地返回用户在TCPClient中输入的反向字符串。例如:

输入:你好 输出:olleh ereht

现在我想改变字符串中的顺序。例如:

输入:你好 输出:那里你好

以下是我的代码,仅用于撤消,如何撤消订单?

//TCPClient

package orderreversetcpclient;

//TCPClient.java
import java.io.*;
import java.net.*;

class OrderReverseTCPClient {
   public static void main(String argv[]) throws Exception
   {
      String sentence;
      String modifiedSentence;
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
      Socket clientSocket;
      clientSocket = new Socket("27.147.162.222", 6323);
      DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
      BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      sentence = inFromUser.readLine();
      outToServer.writeBytes(sentence + '\n');
      modifiedSentence = inFromServer.readLine();
      System.out.println("FROM SERVER: " + modifiedSentence);
      clientSocket.close();
   }
}

// TCPSERVER

package OrderReverseTCPServer;

import java.io.*;
import java.net.*;

class TCPServer {
   public static void main(String argv[]) throws Exception
   {
      String clientSentence;
      //String capitalizedSentence = null;
      ServerSocket welcomeSocket = new ServerSocket(6333);
      while(true) {
         Socket connectionSocket = welcomeSocket.accept();
         BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
         DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
         clientSentence = inFromClient.readLine();
         String sendToClient = new StringBuilder(clientSentence).reverse().toString()+'\n';
         outToClient.writeBytes(sendToClient) ;
      }
   }
}

1 个答案:

答案 0 :(得分:0)

你可以使用类似的东西

public String reverseString(String recievedMessage) {
    // the simpliest splitting. Think about ".,!?" symbols
    String[] words = recievedMessage.split(" ");
    StringBuilder sb = new StringBuilder();
    for (int i = words.length - 1; i > 0 ; i--) {
        // Here space symbol may be enhanced to more difficult cases ".?,"
        sb.append(words[i]).append(" ");
    }
    // to delete last space symbol call trim() function.
    return sb.toString().trim();
}