LeWimbes
LeWimbes

Reputation: 507

How can I parse a string that contains the same symbol I use as a delimiter?

I would like to put some Strings together and split them again afterward. The character I would like to use as a marker for the point where the String is put together should also be allowed to occur in the Strings.

Example:
We want to send a message to someone else. There should not only be the message itself, but also some information about the sender and the receiver.

So we have three Strings: sender, receiver, and text. As a delimiter I use $. That means that the merged String would have the following syntax: sender$receiver$text

As long as there is no $ in sender, receiver, or text, everything is fine and there won’t be a problem when splitting the String again. But when there is a $ in one of the Strings, an unexpected output will be given.

How can I avoid this problem without just creating the rule that $ is not allowed to be used?

Upvotes: 0

Views: 116

Answers (2)

MC Emperor
MC Emperor

Reputation: 22997

You are essentially serializing and deserializing.

The problem with your current approach, that is, using a special token to separate different parts of the body, is that it could lead to errors if that very same token is used within such a part. One can never be sure that the separator will be unique.

That's why people invented the concept of serialization. JSON is a widely used format, see json.org. There are also plenty of parsers for that, for example Gson.

Suppose you have the following class:

class Message {

    private String sender;
    private String receiver;
    private String text;

}

then it can be serialized into this:

{
    "sender": "me",
    "receiver": "you",
    "text": "Almost any char can occur inside this, even \" or \\. They are simply escaped"
}

with a snippet of code like this:

Message message = new Message("me", "you",
    "Almost any char can occur inside this, even \" or \\. They are simply escaped");
    // The Java language itself uses the same escape sequences as JSON.
    // It actually works the same way

// Surprisingly easy to convert Java object to JSON
new Gson().toJson(message);

See? The receiving party can then deserialize it using this snippet:

new Gson().fromJson(receivedString, Message.class);

Upvotes: 3

Maurice Perry
Maurice Perry

Reputation: 9650

When you put the strings together, you could escape the fields and replace the dollars with some escape sequence (\d for instance), and unescape them when reading.

Upvotes: 0

Related Questions