How do I work with a String with parameters?

Asked

Viewed 1,106 times

2

The question seems to be simple and naive, but I never needed to use it, I own a String and inside I want to put parameters to be filled out later, as in php

$string = "o meu nome é $nome";

or as in c, but in c is to show on screen, in case I want to work with String. printf("meu nome é %s", nome);

In java I’ve worked with something similar but when working with connection to the database using PreparedStatement.

My real problem is:
I have a String in this format
https://{paíz}.dominio.com.{paíz}/api/page
The first moment the most obvious is to make concatenations, but since there are several strings in this format, when there are future maintenances I believe that it will be a little more work.

  • I know, but some function should return a new string. I need something similar to Preparedstatement that parameterizes the SQL String

  • I am aware that String are immutable. I want to parameterize a String.

2 answers

5

Strsubstitutor

Another suitable option for simple variable substitutions is the StrSubstitutor apache Commons.

Example:

Map valuesMap = HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog"); 
String templateString = "The ${animal} jumped over the ${target}."; 
StrSubstitutor sub = new StrSubstitutor(valuesMap); 
String resolvedString = sub.replace(templateString); 

The downside of this class is having to use a separate library.

But it is very useful, for example, if you want to let the user type a parameterized template where you will provide the value of the variables and do not want advanced formatting options.

An example is if you want to let the user enter a path pattern for a rotating log file. It could be like this:

/temp/logs/acessos-${data}.log.${numeroArquivo}

And then the system applies the variables data and numeroArquivo when saving the log.

It is possible to modify the prefix and suffix of the variables using another constructor of the class StrSubstitutor, so there’s no need to be stuck to the pattern ${ and }.

This would be a case closer to what is intended in the question.

Messageformat

Beyond the standard of Formatter or String.format(), there is a slightly more advanced option that has support even to pluralize texts, which is more suitable if the intention is to parameterize the texts of the application and do Internationalization and Localization.

This is about the MessageFormat.

Example:

int planet = 7; 
String event = "a disturbance in the Force"; 
String result = MessageFormat.format( "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.", 
    planet, new Date(), event); 

Considerations

Note that these classes have specific applications and their use is unnecessary in the simplest and most common use cases.

  • 1

    Guy Strsubstitutor is really cool. I never imagined anything like it. Very good to know thank you.

  • @nbro I would say that really are unnecessary for most cases, only having more specific applications. It is necessary to understand their purpose. With the format you only have positional access to the parameters while the StrSubstitutor allows you to create templates with named variables based on any map, including environment variables. For example, it is useful to allow the user to enter directory path templates. Now MessageFormat is good for L10n and I18n, so it is the way to keep messages consistent with numerical values without filling the code with Ifs/ternaries

  • @I read what you wrote, but in this case my understanding of the excerpt useless most of the time It was different than what you just explained.

  • @nbro Thanks for the feedback, it was quite helpful.

3


The only solutions I see is to use an external class like Formatter or simply use the Static function format class String. Here is a simple example:

import java.util.Formatter;

public class Test {
    public static void main(String[] args) {
        Formatter f = new Formatter();
        f.format("My name is %s%n", "James");

        String firstName = f.toString();
        String lastName = String.format("My last name is %s%n", "Bond");

        System.out.println(firstName);
        System.out.println(lastName);

        f.close();
    }
}
  • That’s right, only String.format resolves, I saw here http://stackoverflow.com/questions/9643610/java-including-variables-within-strings, I didn’t need to use this Formatter

Browser other questions tagged

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