Format String

2

I have the following sample 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:

  

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

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

asked by anonymous 04.01.2017 / 16:06

3 answers

2

You can do 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 output:

MODERADOR João > uma mensagem.

See here working on ideone.

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

In% w /%, the test is run. There, an instance of main is built, Template is constructed with the desired substitutions, substitutions are performed and the result is displayed.

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

    
04.01.2017 / 16:44
5

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

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

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

If it's a little more complicated, you can use MessageFormat.format(pattern, arguments) ". The first argument to be submitted is a template string containing braces which should be replaced by the values of the arguments parameter. 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, it would look like:

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

    
04.01.2017 / 16:34
0

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

String user = "João";

 String mensagem = "MODERADOR" + user + "> uma mensagem";  
    
04.01.2017 / 16:17