[英]JAVA - How to replace tokens in a string
我有一個像這樣的字符串:
String message = "Hello {0}, the max amount is {1}, {2} ..." ;
其中要替換 {0}、{1}、{2} 的消息位於字符串數組中:
String[] strings = new String[1];
strings[0] = object.CONSTANTE;
strings[1] = object.CONSTANTE1;
strings[2] = object.CONSTANTE2;
當數組中 arguments 的數量與消息中的數量不同時,我想要一個例外。
謝謝你。
作為 JDK 的一部分的MessageFormat class 正是您想要的。
String message = "Hello {0}, the max amount is {1}, {2} ..." ;
String formatted = MessageFormat.format(message, string1, string2, string3);
java.text.MessageFormat
正是您想要的。
class 具有 static 方法格式,可以使用消息和Object[]
調用(可變參數是數組)。
你可以這樣做:
String message = "Hello {0}, the max amount is {1}, {2} ...";
String[] strings = { object.CONSTANTE, object.CONSTANTE1, object.CONSTANTE2 };
String formatted = MessageFormat.format(message, strings);
System.out.println(formatted);
或者,甚至更短:
String formatted = MessageFormat.format("Hello {0}, the max amount is {1}, {2} ...",
object.CONSTANTE, object.CONSTANTE1, object.CONSTANTE2);
System.out.println(formatted);
像這樣試試。
String message = "您好{0},最大金額為{1},{2}..."; 其中要替換 {0}、{1}、{2} 的消息位於字符串數組中:
String[] strings = new String[3];
strings[0] = object.CONSTANTE;
strings[1] = object.CONSTANTE1;
strings[2] = object.CONSTANTE2;
for (int i = 0; i < 3; i++) {
message = message.replace("{"+i+"}", strings[i]);
}
您可以遍歷字符串中的字符並檢查字符是否為“{”,如果是,請檢查以下內容以檢查它是否是令牌。 如果它是令牌,則將其值存儲在變量中。 繼續遍歷字符串,直到找到另一個“{”。 檢查它是否是一個令牌,如果是,並且最后一個存儲它的值更高。 當您完成對字符串的分析后,您的變量將具有標記數量 -1(因為第一個標記為 0)
Java 提供格式化程序 class 用於在字符串內執行替換。
這是一個示例程序,用於根據上述要求替換字符串中的值:
// File name: Demo.java
import java.util.*;
public class Demo {
public static void main(String[] args) {
String[] constants = new String[3];
constants[0] = "CONSTANTE";
constants[1] = "CONSTANTE1";
constants[2] = "CONSTANTE2";
StringBuilder message = new StringBuilder();
Formatter formatter = new Formatter(message);
formatter.format("Hello {%s}, the max amount is {%s}, {%s}",
constants[0], constants[1], constants[2]);
System.out.println(message.toString());
}
}
Output:
> javac Demo.java
> java Demo
Hello {CONSTANTE}, the max amount is {CONSTANTE1}, {CONSTANTE2}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.