Format String

Asked

Viewed 924 times

2

I have the following example code:

String _randomTag = "pvp";
String _randomTag2 = "otherName";
String _format = "{tag} {player} {" + _randomTag + "} {" + _randomTag + "} > {msg}"
String _result = _format.replace("{tag}", "MODERADOR").replace("{player}", "João").replace("{msg}", "uma mensagem.")

The result will be:

"MODERATOR John {pvp} {otherName} > a message."

I want to remove the other 'tags' ({pvp} and {otherName}), with a result like this: "MODERADOR João > uma mensagem.", remembering that the variables _randomTag and _randomTag2 will have random names.

3 answers

5

If it’s something simple, you can use the method format():

String moderator = "João";
int messages = 3;

// João tem 3 mensagens.
String.format("%s tem %s mensagens.", moderator, messages);

If it’s something a little more complicated, you can use MessageFormat.format(pattern, arguments). The first argument to be sent is a template string containing between keys which should be replaced by parameter values arguments. For example:

// Olá! Eu me chamo Krash0
MessageFormat.format("Olá! Eu me chamo {0}.", "Krash0"); 

// Tom Hanks não é meu nome, me chamo Krash0
MessageFormat.format("{1} não é meu nome, me chamo {0}", "Tom Hanks", "Krash0"); 

Applying in your case would be:

String playerName = "João";
String playerType = "MODERADOR";
String gameType   = "pvp";
int messages = 10;

String output = MessageFormat.format("[{0}] {1} [{2}] > {3} mensagens.",
                playerType, playerName, gameType, messages);

// [MODERADOR] João [pvp] > 10 mensagens.

Running on IDEONE

  • 1

    +1 Legal this use of format :)

  • I think the idea was to eliminate [pvp] of output.

2


You can do it like this:

import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;

class Main {
    public static void main(String[] args) {
        String templateTexto = "{tag} {player} {abacaxi} {banana} > {msg}";
        Map<String, String> substituicoes = new HashMap<>();
        substituicoes.put("tag", "MODERADOR");
        substituicoes.put("player", "João");
        substituicoes.put("msg", "uma mensagem.");

        Template template = new Template(templateTexto);
        String substituido = template.substituir(substituicoes);
        System.out.println(substituido);
    }
}

class Template {

    private final String template;
    private final Set<String> tags;

    public Template(String template) {
        this.template = template;
        this.tags = new TreeSet<>();
        StringBuilder nomeVariavel = null;
        boolean variavel = false;
        for (char c : template.toCharArray()) {
            if (!variavel && c == '{') {
                variavel = true;
                nomeVariavel = new StringBuilder();
            } else if (variavel && c == '}') {
                variavel = false;
                tags.add(nomeVariavel.toString());
                nomeVariavel = null;
            } else if (variavel) {
                nomeVariavel.append(c);
            }
        }
    }

    public String substituir(Map<String, String> substituicoes) {
        String texto = template;
        for (Map.Entry<String, String> entry : substituicoes.entrySet()) {
            texto = texto.replace("{" + entry.getKey() + "}", entry.getValue());
        }
        for (String tag : tags) {
            if (substituicoes.containsKey(tag)) continue;
            texto = texto.replace("{" + tag + "} ", "");
            texto = texto.replace("{" + tag + "}", "");
        }
        return texto;
    }
}

Here’s the way out:

MODERADOR João > uma mensagem.

See here working on ideone.

In this code, the class Template represents the text with the tags. It has a method to do the substitution, according to a Map. Note that the class implementation Template is a small compiler (its constructor is based on a two-state automaton).

In the main, his test is carried out. There, an instance of the Template, is built the Map with the desired substitutions, the substitutions are performed and the result is displayed.

The method substituir only starts with the template text and exits by replacing the tags with the substitutes specified in Map. After that, the elements that are not found in the Map, that match the other tags, are deleted. Note the detail that he also cares about taking away any space in the template after a tag that will be deleted.

  • 1

    This code was exactly what I needed, thank you!

  • 1

    @Krash0 I see that you accepted the other answer, even saying that this is what you answered, there was some mistake?

-1

In the case of the above code {pvp} {otherName} are not mentioned in the Replaces. We can simplify this code.

String user = "João";

 String mensagem = "MODERADOR" + user + "> uma mensagem";  
  • 2

    From what he implied the question, this solution is not what the OP wants. He seems to want to work with "tags"

  • It is not possible, the replace’s in the _result variable is precisely to replace the "tags" by their proper name.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.