java – Use more than one variable in the same sentence (replace)

Question:

In a field I need to replace two words with any other two.

Example: Mr(a) v1, the value of your invoice is v2 reais. How it should look:
Mr. Joao , the value of your invoice is 10.00 reais.

So I have the following method below.

String mensagemI = txtMensagem.getText();

        String var1 = txtVariavel1.getText();
        String var2 = txtVariavel2.getText();
        String var3 = txtVariavel3.getText();

        String mensagemF = mensagemI.replaceAll("v1", var1);

        System.out.println(mensagemF);

But this way, I can change only one word of the sentence, in this case v1.

Is there any other method, where I can change two words in one sentence?

Thanks.

Answer:

From what I read you want to replace:

Mr(a) V1 , the value of your invoice is V2 reais.

But in the code you're replacing v1 (lowercase).

    String mensagemI = "Sr(a) V1, o valor da sua fatura é de V2 reais.\nPague sua fatura em dia V1.";

    String var1 = "Joao";
    String var2 = "10,00";

    String mensagemF = mensagemI.replaceAll("V1", var1).replaceAll("V2", var2);

    System.out.println(mensagemF);

Just go calling the replaceAll function passing the pattern and the value that will replace. 🙂

Scroll to Top