[英]String.format() format for last characters of a string
是否有可能設置String.format參數,以便使用輸入的最后N
字符,即:
String s = String.format("%1${N}s", "abcdef");
所以s
包含"def"
? 這在您可以說的腳本語言中很常見
exp = "abcdef"
s = exp[-3]
編輯
好的,所以我不想格式化我的數據並在將它放入String#format
函數時處理它。 這就是格式描述的重點。 這種格式描述代表了一種模塊化形式,如果我必須預先格式化我的輸入數據,盡管有一個格式化程序,這種形式會大打折扣......
不幸的是,即使是現在(y2017) Java 8 Formatter也不支持“substring”。
你可以試試:
Freemarker和slicing (substrings)
:
// string 'abcde', evaluates to "bcd" <#assign s="abcde"> ${s[1..3]}
Spring Expression Language(SpEL)和expressions methods
:
// string literal 'abcde', evaluates to "bcd" ExpressionParser parser = new SpelExpressionParser(); String sub = parser.parseExpression("'abcde'.substring(2, 4)").getValue(String.class);
String#substring(int index)
與腳本示例的作用相同:
String a = "abcdef";
String b = String.format("%s", a.substring(3));
我不清楚String.format
是否具有這種功能。 但是使用String
功能,可以實現。
int n = 10;
String a = "01234567891234";
// Split into to strings.
String lastString = a.substring(a.length() - n);
String firstString = a.substring(0, a.length() - n);
// Format second string and result is concatenated with first.
String formattedLastString = String.format("%15s", lastString);
String formattedString = firstString.concat(formattedLastString);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.