Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何参数化字符串并替换参数_Java_String_Jakarta Ee - Fatal编程技术网

Java 如何参数化字符串并替换参数

Java 如何参数化字符串并替换参数,java,string,jakarta-ee,Java,String,Jakarta Ee,我有一个由最终用户输入的字符串,这个字符串的格式应该是显示{2}的{0}到{1},我想用我从后端计算的数字替换花括号中的参数。 与属性文件中的字符串完全相同。 我该怎么做 样本输入: Showing {0} to {1} of {2} 样本输出: Showing 1 to 12 of 30 您可以通过以下方式执行此操作: 您可以使用String.format() 下面是如何做到这一点 int a = 1; int b = 12; int c = 30; String myFormatted

我有一个由最终用户输入的字符串,这个字符串的格式应该是
显示{2}
的{0}到{1},我想用我从后端计算的数字替换花括号中的参数。 与属性文件中的字符串完全相同。
我该怎么做

样本输入:

Showing {0} to {1} of {2} 
样本输出:

Showing 1 to 12 of 30
您可以通过以下方式执行此操作:


您可以使用
String.format()

下面是如何做到这一点

int a = 1;
int b = 12;
int c = 30;
String myFormattedString = String.format("Showing %d to %d of %d", a, b, c); 
// Value of myFormattedString is 'Showing 1 to 12 of 30'

您应该使用正则表达式来获取这些参数的值

这样做,您必须考虑下面的代码示例:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = p.matcher("Showing 1 to 12 of 30");


int[] numbers; 
int i = 0;
while(matcher.find()){
 numbers[i++] = Integer.parseInt(matcher.group());
}
因此,现在所有这些数字都在int[]中。

试试下面这样的正则表达式:

public static void main(String[] args) {
    String s = "Showing {0} to {1} of {2}";
    int arr[] = { 10, 20, 30 };
    s = s.replaceAll("(.*)(\\d)(.*)(\\d)(.*)(\\d)", "$1" + arr[0] + "$3"
            + arr[1] + "$5" + arr[2]);
    System.out.println(s);
}
O/p:


您可以使用java.text.MessageFormat包中的MessageFormat,如下所示

public static void main(String[] args) {
        String a = "this is {0} of {1} another String";
        System.out.println(MessageFormat.format(a, "replacement1", "replacement2"));
    }
O/p
“这是replacement2的replacement1另一个字符串”

如果有多个参数和replacement,则可以使用String.format,但如果只有一个参数要替换,则可以使用

String myselfUrl = https://url.abc/{cloudId}/api/myself
StringUtils.replace(myselfUrl, "{cloudId}", 123456);
将导致

https://url.abc/123456/api/myself

请向我们展示示例输入和输出。您希望类和代码如下所示well@Vihar我在寻找类似的东西:String myString=“显示{0}到{1}的{2}”;字符串结果=SomeClass.someStaticMethod(myString,1,12,30);正如我所说。您想要的类是MessageFormat。它正是你所要求的。去读一读吧。
String myselfUrl = https://url.abc/{cloudId}/api/myself
StringUtils.replace(myselfUrl, "{cloudId}", 123456);
https://url.abc/123456/api/myself