English 中文(简体)
识别字符数组中的特殊字符
原标题:Identify a special character in an array of chars
  • 时间:2011-02-11 21:00:12
  •  标签:
  • java
  • arrays

我正在编写一个客户端/服务器应用程序。我有一个Message类,它有几个String字段。我已经编写了以下方法来返回这些字段的char[]:

public char[] toArrayOfChar()
{
    String str = "";
    char[] charr;
    str += from;
    str += "
";
    str += to;
    str += "
";
    str += header;
    str += "
";
    str += body;
    str += "
";
    str += header;
    str += "
";
    charr = str.toCharArray();

    return charr;
}

现在,我想将每个字段分开,并在将其从客户端发送到服务器后将其转换为字符串。如何识别每个字段末尾的回车符和换行符?

最佳回答

对于您的实际问题,已经给出了很好的答案,但关于您的代码风格:

使用多个String+=调用的效率非常低。这是一个效率高得多的版本。

首先为cr+lf定义一个常数:

private static final String CRLF = "
";

现在使用StringBuilder来构建String,如下所示:

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();
}

这更容易阅读,也更高效(您的版本必须为每个+=调用创建一个新的String实例)。

此外,也许您应该在对象的toString()方法中写下这段代码(减去.toCharArray()行),然后执行this.toString().toCharArray()以获得char[]。利用标准机制总是一种很好的做法,这就是toString()方法的作用,创建对象的字符串表示

问题回答

我建议您查看PrintWriterBufferedReader类,如官方追踪:从套接字读取和写入套接字

使用这些类,您可以简单地使用

out.println(from);
out.println(to);
out.println(header);
out.println(body);

并使用读取

String from   = bufferedReader.readLine();
String to     = bufferedReader.readLine();
String header = bufferedReader.readLine();
String body   = bufferedReader.readLine();




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签