简体   繁体   English

String.format()格式,用于字符串的最后一个字符

[英]String.format() format for last characters of a string

is there a possibility to set a String.format argument such that the last N characters of the input are used, ie something like: 是否有可能设置String.format参数,以便使用输入的最后N字符,即:

String s = String.format("%1${N}s", "abcdef");

so that s contains "def" ? 所以s包含"def" This is common in script languages where you can say 这在您可以说的脚本语言中很常见

exp = "abcdef"
s = exp[-3]

EDIT 编辑

OK, so i don't want to format my data AND handle it when putting it into the String#format function. 好的,所以我不想格式化我的数据并在将它放入String#format函数时处理它。 That's the whole point of the format description here. 这就是格式描述的重点。 This format description represents a form of modularity, which is considerably broken if I have to format my input data beforehand although there is a formatter to come... 这种格式描述代表了一种模块化形式,如果我必须预先格式化我的输入数据,尽管有一个格式化程序,这种形式会大打折扣......

Unfortunately, even now (y2017) Java 8 Formatter doesn't support "substring". 不幸的是,即使是现在(y2017) Java 8 Formatter也不支持“substring”。

You can try: 你可以试试:

  • Freemarker and slicing (substrings) : Freemarker和slicing (substrings)

     // string 'abcde', evaluates to "bcd" <#assign s="abcde"> ${s[1..3]} 
  • Spring Expression Language (SpEL) and expressions methods : 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) does the same thing as your script example: String#substring(int index)与脚本示例的作用相同:

String a = "abcdef";
String b = String.format("%s", a.substring(3));

I am not clear whether String.format has this kind of function or not. 我不清楚String.format是否具有这种功能。 But using functions of String , it can be realized. 但是使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM