How to read from raw file and use in String.format

I want to read data from a raw file and replace the format in the text.

For example ... In the raw file:

hello {0}, my name id {1}, my age is {2}....

      

When I use String.format like below, the text loses its indentation.

String data = readTextFile(this, R.raw.input);
data = String.format(data, "world", "josh", "3"); 

      

Does anyone know how to do this without losing indentation?

+3


source to share


3 answers


I found a solution for my problem.

there is a need for one more variable, it cannot be assigned to one variable



String data = readTextFile(this, R.raw.input);
String output = String.format(data, "world", "josh", "3");

      

0


source


The code you provided is more like String.format like C # . String.format in Java doesn't work that way, it's more like printf.

You can manipulate your input this way.

String input = "hello %s, my name id %s, my age is %s";
String.format(input, "world", "josh", "3");

      

Output: hello world, my name id josh, my age is 3



indentation must be the same

EDIT

If you want to use parentheses, you can use MessageFormat.format

instead String.format

.

String messageInput = "hello {0}, my name id {1}, my age is {2}";
MessageFormat.format(messageInput,"world", "josh", "3");

      

+1


source


You can use Regular Explessions with a pattern like this "{/d++}"

::

String format (String input, String... args) {
    Pattern p = Pattern.compile("{/d++}");
    String[] parts = p.split(input);
    StringBuilder builder = new StringBuilder("");
    int limit = Math.min(args.length, parts.length);
    for(int i = 0; i < limit; i++){
        builder.append(parts[i]).append(args[i]);
    }
    return builder.toString();
}

      

0


source







All Articles