16

我正在传递由 {} 填充符和文本组合而成的文本。我正在尝试用一些值填充 {} 并尝试使用 MessageFormat。

String sss = "{0}SomeText{1}\'.{2}SomeText{2}SomeText{0}{0}SomeText{2}{0}SomeText{0}{1}SomeText{0}{2}{0}{0}{1}{0}{2}{0}{0}{2}{0}{0}{1}{0}{2}{0}";

Object[] testArgs = {"nits1", "Nits2","nits#"};

System.out.println(MessageFormat.format(sss,testArgs));

输出

nits1SomeTextNits2.{2}SomeText{2}SomeText{0}{0}SomeText{2}{0}SomeText{0}{1}SomeText{0}{2}{0}{0}{1}{0}{2}{0}{0}{2}{0}{0}{1}{0}{2}{0}
4

2 回答 2

41

必须使用双单引号对单引号进行转义:

String sss = "{0}SomeText{1}''.{2}S..."
于 2012-06-12T11:34:14.173 回答
1

我的错误是,我没有使用方法'format(..)'的返回值

错误代码:

MessageFormat.format(sss, testArgs);
System.out.println(sss);

正确代码:

String newString = MessageFormat.format(sss, testArgs);
System.out.println(newString);
于 2020-07-22T14:01:31.487 回答