0

Here is a string template read from file.

Name: %s
Age: %d

After I read it from file, I want to format this string using given name and age.

var template = File("file_path").readText()

MessageFormat.format(template, "Bod", 123)

print(template)

However I cannot format template. Its output is.

Name: %s
Age: %d
4
  • True, I removed the flag Commented Apr 27, 2018 at 12:26
  • 1
    You mixed MessageFormat and String formatting. String.format use %s where MessageFormat use {0} Commented Apr 27, 2018 at 12:28
  • @AxelH Yes you are right. Thanks a lot. Commented Apr 27, 2018 at 12:29
  • 你这样整是不行的,要传一个数组的话建议你使用我之前给的那种直接把数组放在第二个参数的做法(String.format("%s", *array) Commented Apr 27, 2018 at 16:22

1 Answer 1

2

You should either use String.format instead of MessageFormat.format or use {0}/{1} instead of %s/%d.

Sign up to request clarification or add additional context in comments.

4 Comments

If i want to put an array, what can I do?
Just pass individual array elements.
@DodgyCodeException Do I have to put array elements one by one? Can I directly pass array?
@CoXier if the array contains all of your arguments you can pass it as a vararg parameter using the * operator (*array), this is the Kotlin equivalent of passing a T[] to a T... in Java

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.