Identify a special character in an array of chars
I am writing a client/server application. I have a Message class with several String fields. I have written the following method to return a char[] of these fields:
public char[] toArrayOfChar()
{
String str = "";
char[] charr;
str += from;
str += "\r\n";
str += to;
str += "\r\n";
str += header;
str += "\r\n";
str += body;
str += "\r\n";
str += header;
str += "\r\n";
charr = str.toCharArray();
return charr;
}
Now I want to separate each field and convert it to a String after I have sent it from client to server. How do I identify the carriage return and line feed characters a开发者_如何学运维t the end of each field?
For your actual question, good answers have been given, but about your code style:
It's horribly inefficient to use multiple String += calls. Here's a much more efficient version.
First define a constant for cr + lf:
private static final String CRLF = "\r\n";
Now use StringBuilder
to build the String
, like this:
public char[] toArrayOfChar()
{
return new StringBuilder()
.append(from).append(CRLF)
.append(to).append(CRLF)
.append(header).append(CRLF)
.append(body).append(CRLF)
.append(header).append(CRLF)
.toString()
.toCharArray();
}
This is both easier to read and more efficient (your version has to create a new String instance for every += call).
Also, maybe you should just write this code (minus the .toCharArray()
line) in your object's toString()
method and do this.toString().toCharArray()
to get the char[]
. It's always a good practice to utilize standard mechanisms, this is what the toString()
method is for, create a String representation of the object.
I suggest you look into the PrintWriter
and BufferedReader
classes, as suggested in the official trail: Reading from and Writing to Sockets.
Using these classes you can simply send your strings using
out.println(from);
out.println(to);
out.println(header);
out.println(body);
and read using
String from = bufferedReader.readLine();
String to = bufferedReader.readLine();
String header = bufferedReader.readLine();
String body = bufferedReader.readLine();
精彩评论